package com.xbongbong.saas.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Joiner;
import com.xbongbong.i18n.util.I18nMessageUtil;
import com.xbongbong.paas.constant.MessageConstant;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.domain.entity.PaasFormEntity;
import com.xbongbong.paas.domain.entity.PaasFormExplainEntity;
import com.xbongbong.paas.domain.entity.ext.PaasAttachmentEntityExt;
import com.xbongbong.paas.domain.entity.ext.PaasFormDataEntityExt;
import com.xbongbong.paas.domain.entity.ext.PaasFormEntityExt;
import com.xbongbong.paas.elasticsearch.model.PaasEsModel;
import com.xbongbong.paas.elasticsearch.pojo.XbbAggregatedPage;
import com.xbongbong.paas.elasticsearch.pojo.dto.InsertDTO;
import com.xbongbong.paas.elasticsearch.util.EsUtil;
import com.xbongbong.paas.elasticsearch.util.XbbElasticsearchRestTemplate;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.enums.FieldTypeEnum;
import com.xbongbong.paas.enums.IndexTypeEnum;
import com.xbongbong.paas.field.FieldAttrEntity;
import com.xbongbong.paas.field.LinkDetailPojo;
import com.xbongbong.paas.help.FormDataListSearchHelp;
import com.xbongbong.paas.log.MongoLogHelp;
import com.xbongbong.paas.log.constant.LogMemoConstant;
import com.xbongbong.paas.model.PaasFormExplainModel;
import com.xbongbong.paas.pojo.ButtonPojo;
import com.xbongbong.paas.pojo.DataDetailPojo;
import com.xbongbong.paas.pojo.DetailTabPojo;
import com.xbongbong.paas.pojo.DetailTitlePojo;
import com.xbongbong.paas.pojo.FieldAttrEntityForImport;
import com.xbongbong.paas.pojo.dto.FormDataAddDTO;
import com.xbongbong.paas.pojo.dto.FormDataGetDTO;
import com.xbongbong.paas.pojo.dto.FormDataListDTO;
import com.xbongbong.paas.pojo.dto.ImportFormDataDTO;
import com.xbongbong.paas.pojo.imports.CellTitlePojo;
import com.xbongbong.paas.pojo.imports.CellValuePojo;
import com.xbongbong.paas.pojo.imports.RowGroupPojo;
import com.xbongbong.paas.pojo.vo.FormDataAddVO;
import com.xbongbong.paas.pojo.vo.FormDataDeleteBatchVO;
import com.xbongbong.paas.pojo.vo.FormDataGetVO;
import com.xbongbong.paas.pojo.vo.PaasFormDataEsListVO;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.helper.PageHelper;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.toolbox.util.DateTimeUtil;
import com.xbongbong.paas.toolbox.util.StringUtil;
import com.xbongbong.paas.toolbox.wrap.BaseVO;
import com.xbongbong.paas.util.ExplainUtil;
import com.xbongbong.pro.applist.pojo.AppListPojo;
import com.xbongbong.pro.applist.pojo.vo.ListAppVO;
import com.xbongbong.pro.constant.ElasticConstant;
import com.xbongbong.pro.enums.SaasMarkEnum;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.ThirdPartyUsageErrorCodeEnum;
import com.xbongbong.pro.formdata.pojo.dto.FormDataDetailDTO;
import com.xbongbong.pro.formdata.pojo.vo.FormDataDetailVO;
import com.xbongbong.pro.knowledge.base.pojo.dto.BatchDealTagDTO;
import com.xbongbong.pro.knowledge.base.pojo.dto.KnowledgeAddDTO;
import com.xbongbong.pro.knowledge.base.pojo.dto.KnowledgeContentDTO;
import com.xbongbong.pro.knowledge.base.pojo.dto.KnowledgeEsAddDTO;
import com.xbongbong.pro.knowledge.base.pojo.dto.KnowledgeListDTO;
import com.xbongbong.pro.knowledge.base.pojo.dto.KnowledgeOperationDTO;
import com.xbongbong.pro.knowledge.base.pojo.vo.KnowledgeVO;
import com.xbongbong.pro.log.pojo.DetailLogPojo;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.constant.StringConstant;
import com.xbongbong.saas.domain.entity.CabinetFileEntity;
import com.xbongbong.saas.domain.entity.KnowledgeBaseEntity;
import com.xbongbong.saas.domain.entity.KnowledgeCatalogueEntity;
import com.xbongbong.saas.domain.entity.KnowledgeDataEntity;
import com.xbongbong.saas.domain.entity.KnowledgeTagEntity;
import com.xbongbong.saas.enums.BusinessDetailButtonEnum;
import com.xbongbong.saas.enums.BusinessDetailTabEnum;
import com.xbongbong.saas.enums.KnowledgeErrorCodeEnum;
import com.xbongbong.saas.enums.ListBatchEnum;
import com.xbongbong.saas.enums.ListTopButtonEnum;
import com.xbongbong.saas.enums.OperateModuleTypeEnum;
import com.xbongbong.saas.enums.OperateTypeEnum;
import com.xbongbong.saas.enums.SaasButtonEnum;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.enums.business.KnowledgeDataEnum;
import com.xbongbong.saas.enums.dictionary.KnowledgeContentTypeEnum;
import com.xbongbong.saas.enums.dictionary.KnowledgeDataStatusEnum;
import com.xbongbong.saas.help.ImportHelper;
import com.xbongbong.saas.help.KnowledgeBaseHelp;
import com.xbongbong.saas.model.CabinetFileModel;
import com.xbongbong.saas.model.KnowledgeBaseModel;
import com.xbongbong.saas.model.KnowledgeCatalogueModel;
import com.xbongbong.saas.model.KnowledgeDataModel;
import com.xbongbong.saas.model.KnowledgeTagModel;
import com.xbongbong.saas.service.KnowledgeDataService;
import com.xbongbong.saas.service.toolbox.help.LogHelp;
import com.xbongbong.sys.domain.entity.UserEntity;
import com.xbongbong.sys.model.UserModel;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.FieldSortBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.StringJoiner;
import java.util.stream.Collectors;

import static org.elasticsearch.index.query.QueryBuilders.boolQuery;
import static org.elasticsearch.index.query.QueryBuilders.matchPhraseQuery;
import static org.elasticsearch.index.query.QueryBuilders.termQuery;
import static org.elasticsearch.index.query.QueryBuilders.termsQuery;

/**
 * 知识库处理接口实现
 *
 * @author ruansicheng
 * @version v1.0
 * @date 2022/06/21
 * @since v1.0
 */
@Slf4j
@Service("KnowledgeDataService")
public class KnowledgeDataServiceImpl implements KnowledgeDataService {
    private static final Logger LOG = LoggerFactory.getLogger(KnowledgeDataServiceImpl.class);
    @Resource
    private KnowledgeDataModel knowledgeDataModel;
    @Resource
    private PaasEsModel paasEsModel;
    @Resource
    private MongoLogHelp mongoLogHelp;
    @Resource
    private FormDataListSearchHelp formDataListSearchHelp;
    @Resource
    private XbbElasticsearchRestTemplate xbbElasticsearchRestTemplate;
    @Resource
    private PaasFormExplainModel paasFormExplainModel;
    @Resource
    private UserModel userModel;
    @Resource
    private KnowledgeCatalogueModel knowledgeCatalogueModel;
    @Resource
    private KnowledgeTagModel knowledgeTagModel;
    @Resource
    private KnowledgeBaseModel knowledgeBaseModel;
    @Resource
    private KnowledgeBaseHelp knowledgeBaseHelp;
    @Resource
    private ImportHelper importHelper;
    @Resource
    private LogHelp logHelp;
    @Resource
    private CabinetFileModel cabinetFileModel;

    @Override
    @Transactional
    public FormDataAddVO addKnowledge(KnowledgeAddDTO knowledgeAddDTO) throws XbbException {
        FormDataAddVO formDataAddVO = new FormDataAddVO();
        //参数校验
        this.knowledgeCheck(knowledgeAddDTO);
        //知识条目实体赋值
        KnowledgeDataEntity knowledgeDataEntity = new KnowledgeDataEntity();
        this.dealKnowledgeDataData(knowledgeAddDTO, knowledgeDataEntity);
        knowledgeDataModel.insert(knowledgeDataEntity);
        //插入es
        KnowledgeEsAddDTO knowledgeEsAddDTO = this.initAddEsData(knowledgeDataEntity, knowledgeAddDTO);
        InsertDTO insertDTO = paasEsModel.getSaveDTO(knowledgeEsAddDTO, IndexTypeEnum.IDX_SAAS_KNOWLEDGE_DATA);
        paasEsModel.insert(insertDTO);
        formDataAddVO.setMsg(I18nMessageUtil.getMessage(MessageConstant.FORM_ADD_RETURN_MSG));
        formDataAddVO.setCode(PaasConstant.FORM_ADD_RETURN_CODE);
        formDataAddVO.setDataId(knowledgeDataEntity.getId());
        formDataAddVO.setFormDataId(knowledgeDataEntity.getId());
        //更新知识库的更新时间
        updateKnowledgeUpdateTime(knowledgeDataEntity.getKnowledgeBaseId(), knowledgeDataEntity.getCorpid());
        // 数据新增完成后，将附件保存到统计表中
        List<PaasAttachmentEntityExt> appendix = knowledgeAddDTO.getAppendix();
        if (CollectionsUtil.isNotEmpty(appendix)) {
            insertCabinetFile(knowledgeAddDTO.getCorpid(), knowledgeAddDTO.getUserId(), knowledgeDataEntity.getId(), appendix.get(0));
        }
        // 操作日志
        KnowledgeBaseEntity baseEntity = knowledgeBaseModel.getByKey(knowledgeAddDTO.getKnowledgeBaseId(), knowledgeAddDTO.getCorpid());
        String memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_ADD_KNOWLEDGE_DATA), knowledgeAddDTO.getLoginUser().getName(), baseEntity.getKnowledgeName(), knowledgeAddDTO.getTitle());
        JSONObject newObj = JSONObject.parseObject(JSON.toJSONString(knowledgeDataEntity));
        List<DetailLogPojo> detailArr = logHelp.getDetailArr4Normal(knowledgeAddDTO.getCorpid(), OperateModuleTypeEnum.KNOWLEDGE_BASE, newObj, newObj);
        mongoLogHelp.buildLog4DetailArr(detailArr, knowledgeAddDTO.getCorpid(), knowledgeAddDTO.getLoginUser().getUserId(), knowledgeAddDTO.getLoginUser().getName(), OperateModuleTypeEnum.KNOWLEDGE_BASE, OperateTypeEnum.NEW, knowledgeDataEntity.getId().toString(), knowledgeAddDTO.getTitle(), memo, knowledgeAddDTO.getHttpHeader());
        return formDataAddVO;
    }

    @Override
    public FormDataDeleteBatchVO deleteBatch(KnowledgeOperationDTO knowledgeOperationDTO) throws XbbException {
        FormDataDeleteBatchVO formDataDeleteBatchVO = new FormDataDeleteBatchVO();
        Map<String, Object> paramMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        paramMap.put("idIn", knowledgeOperationDTO.getIds());
        paramMap.put("knowledgeBaseId", knowledgeOperationDTO.getKnowledgeBaseId());
        paramMap.put("corpid", knowledgeOperationDTO.getCorpid());
        paramMap.put("del", 0);
        List<KnowledgeDataEntity> knowledgeDataEntities = knowledgeDataModel.findEntitys(paramMap);
        if (CollectionsUtil.isEmpty(knowledgeDataEntities)) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
        }
        String corpid = knowledgeOperationDTO.getCorpid();
        List<InsertDTO> insertDTOList = new ArrayList<>();
        //同步ES参数赋值处理
        Map<String, Object> map = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        map.put(StringConstant.UPDATE_TIME, DateTimeUtil.getInt());
        map.put(StringConstant.DEL, DelEnum.DELETE.getDel());
        map.put(KnowledgeDataEnum.UPDATE_ID.getAttr(), knowledgeOperationDTO.getUserId());
        for (KnowledgeDataEntity entity : knowledgeDataEntities) {
            InsertDTO insertDTO = new InsertDTO();
            insertDTO.setEsId(corpid + "_" + entity.getId());
            insertDTO.setIndexTypeEnum(IndexTypeEnum.IDX_SAAS_KNOWLEDGE_DATA);
            insertDTO.setIndex(IndexTypeEnum.IDX_SAAS_KNOWLEDGE_DATA.getIndex());
            insertDTO.setType(IndexTypeEnum.IDX_SAAS_KNOWLEDGE_DATA.getType());
            insertDTO.setSource(map);
            insertDTOList.add(insertDTO);
            entity.setDel(DelEnum.DELETE.getDel());
            entity.setUpdateId(knowledgeOperationDTO.getUserId());
            entity.setUpdateTime(DateTimeUtil.getInt());
        }
        Integer success = knowledgeDataModel.updateBatch(knowledgeDataEntities, corpid);
        paasEsModel.updateBatch(insertDTOList);
        // 操作日志
        KnowledgeBaseEntity baseEntity = knowledgeBaseModel.getByKey(knowledgeOperationDTO.getKnowledgeBaseId(), knowledgeOperationDTO.getCorpid());
        for (KnowledgeDataEntity entity : knowledgeDataEntities) {
            String memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_DELETE_KNOWLEDGE_DATA), knowledgeOperationDTO.getLoginUser().getName(), baseEntity.getKnowledgeName(), entity.getTitle());
            mongoLogHelp.buildLog4DetailArr(null, corpid, knowledgeOperationDTO.getLoginUser().getUserId(), knowledgeOperationDTO.getLoginUser().getName(), OperateModuleTypeEnum.KNOWLEDGE_BASE, OperateTypeEnum.DELETE, entity.getId().toString(), entity.getTitle(), memo, knowledgeOperationDTO.getHttpHeader());
        }
        return formDataDeleteBatchVO;
    }

    /**
     * 编辑获取实体数据接口
     *
     * @param knowledgeOperationDTO
     * @return
     * @throws XbbException
     */
    @Override
    public KnowledgeVO knowledgeUpdateGet(KnowledgeOperationDTO knowledgeOperationDTO) throws XbbException {
        KnowledgeVO knowledgeVO = new KnowledgeVO();
        Long id = knowledgeOperationDTO.getIds().get(0);
        String corpid = knowledgeOperationDTO.getCorpid();
        Integer businessType = knowledgeOperationDTO.getBusinessType();
        KnowledgeDataEntity knowledgeDataEntity = knowledgeDataModel.getByKey(id, corpid);
        //获取目录
        KnowledgeCatalogueEntity knowledgeCatalogueEntity = knowledgeCatalogueModel.getByKey(knowledgeDataEntity.getCatalogueId(), corpid);
        String appendixStr = knowledgeDataEntity.getAppendix();
        if (StringUtil.isNotEmpty(appendixStr)) {
            List<PaasAttachmentEntityExt> appendix = JSONArray.parseArray(appendixStr, PaasAttachmentEntityExt.class);
            knowledgeVO.setAppendix(appendix);
        }
        if (StringUtil.isNotEmpty(knowledgeDataEntity.getExpandConsult())) {
            List<String> expandConsult = JSONArray.parseArray(knowledgeDataEntity.getExpandConsult(), String.class);
            knowledgeVO.setExpandConsult(expandConsult);
        }
        if (StringUtil.isNotEmpty(knowledgeDataEntity.getKeywords())) {
            List<String> keywords = JSONArray.parseArray(knowledgeDataEntity.getKeywords(), String.class);
            knowledgeVO.setKeywords(keywords);
        }
        knowledgeVO.setContent(JSONArray.parseArray(knowledgeDataEntity.getContentArray(), KnowledgeContentDTO.class));
        knowledgeVO.setBusinessType(businessType);
        knowledgeVO.setId(knowledgeDataEntity.getId());
        knowledgeVO.setCatalogueId(knowledgeDataEntity.getCatalogueId());
        knowledgeVO.setCatalogueName(knowledgeCatalogueEntity.getName());
        knowledgeVO.setTitle(knowledgeDataEntity.getTitle());
        knowledgeVO.setKnowledgeBaseId(knowledgeDataEntity.getKnowledgeBaseId());
        // 标签
        JSONArray tags = new JSONArray();
        if (Objects.nonNull(knowledgeDataEntity.getLabel()) && CollectionsUtil.isNotEmpty(JSONArray.parseArray(knowledgeDataEntity.getLabel(), String.class))) {
            Map<String, Object> paramMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            paramMap.put("corpid", corpid);
            paramMap.put("del", 0);
            paramMap.put("idIn", JSONArray.parseArray(knowledgeDataEntity.getLabel(), String.class));
            List<KnowledgeTagEntity> knowledgeTagEntities = knowledgeTagModel.findEntitys(paramMap);
            for (KnowledgeTagEntity knowledgeTagEntity : knowledgeTagEntities) {
                JSONObject object = new JSONObject();
                if (Objects.nonNull(knowledgeTagEntity)) {
                    object.put("id", knowledgeTagEntity.getId());
                    object.put("name", knowledgeTagEntity.getName());
                    object.put("parentTagId", knowledgeTagEntity.getParentId());
                    object.put("color", knowledgeTagEntity.getColor());
                    tags.add(object);
                }
            }
        }
        knowledgeVO.setLabel(tags);
        return knowledgeVO;
    }

    @Override
    public KnowledgeVO update(KnowledgeAddDTO knowledgeAddDTO) throws XbbException {
        KnowledgeVO knowledgeVO = new KnowledgeVO();
        KnowledgeDataEntity oldKnowledgeDataEntity = knowledgeDataModel.getByKey(knowledgeAddDTO.getId(), knowledgeAddDTO.getCorpid());
        KnowledgeDataEntity knowledgeDataEntity = new KnowledgeDataEntity();
        this.knowledgeCheck(knowledgeAddDTO);
        long now = DateTimeUtil.getInt();
        if (CollectionsUtil.isNotEmpty(knowledgeAddDTO.getAppendix())) {
            knowledgeDataEntity.setAppendix(JSONObject.toJSONString(knowledgeAddDTO.getAppendix()));
        } else {
            knowledgeDataEntity.setAppendix("[]");
        }
        if (CollectionsUtil.isNotEmpty(knowledgeAddDTO.getKeywords())) {
            knowledgeDataEntity.setKeywords(JSONObject.toJSONString(knowledgeAddDTO.getKeywords()));
        } else {
            knowledgeDataEntity.setKeywords("[]");
        }
        knowledgeDataEntity.setContent(knowledgeAddDTO.getContent());
        if (CollectionsUtil.isNotEmpty(knowledgeAddDTO.getExpandConsult())) {
            knowledgeDataEntity.setExpandConsult(JSONObject.toJSONString(knowledgeAddDTO.getExpandConsult()));
        } else {
            knowledgeDataEntity.setExpandConsult("[]");
        }
        if (Objects.nonNull(knowledgeAddDTO.getLabel())) {
            knowledgeDataEntity.setLabel(JSONObject.toJSONString(knowledgeAddDTO.getLabel()));
        } else {
            knowledgeDataEntity.setLabel("[]");
        }
        knowledgeDataEntity.setCatalogueId(knowledgeAddDTO.getCatalogueId());
        //处理建议回复
        String content = getContentStringByContentArray(knowledgeAddDTO.getContentArray());
        knowledgeDataEntity.setContent(content);
        knowledgeDataEntity.setContentArray(JSONObject.toJSONString(knowledgeAddDTO.getContentArray()));
        knowledgeDataEntity.setTitle(knowledgeAddDTO.getTitle());
        knowledgeDataEntity.setUpdateTime(now);
        knowledgeDataEntity.setCorpid(knowledgeAddDTO.getCorpid());
        knowledgeDataEntity.setUpdateId(knowledgeAddDTO.getUserId());
        knowledgeDataEntity.setId(knowledgeAddDTO.getId());
        Integer success = knowledgeDataModel.update(knowledgeDataEntity);
        //更新es
        InsertDTO insertDTO = new InsertDTO();
        String corpid = knowledgeAddDTO.getCorpid();
        insertDTO.setEsId(corpid + "_" + knowledgeDataEntity.getId());
        KnowledgeEsAddDTO knowledgeEsAddDTO = this.initAddEsData(knowledgeDataEntity, knowledgeAddDTO);
        insertDTO.setSource(BeanUtil.convertBean2Map(knowledgeEsAddDTO, true, true));
        insertDTO.setIndexTypeEnum(IndexTypeEnum.IDX_SAAS_KNOWLEDGE_DATA);
        paasEsModel.update(insertDTO);
        //更新知识库的更新时间
        updateKnowledgeUpdateTime(oldKnowledgeDataEntity.getKnowledgeBaseId(), corpid);
        List<PaasAttachmentEntityExt> appendix = knowledgeAddDTO.getAppendix();
        if (CollectionsUtil.isNotEmpty(appendix)) {
            PaasAttachmentEntityExt paasAttachmentEntityExt = appendix.get(0);
            List<CabinetFileEntity> cabinetFileEntityList = cabinetFileModel.getCabinetFilesByIdIn(corpid, Arrays.asList(knowledgeDataEntity.getId()), XbbRefTypeEnum.KNOWLEDGE_BASE.getCode());
            if (CollectionsUtil.isEmpty(cabinetFileEntityList)) {
                insertCabinetFile(knowledgeAddDTO.getCorpid(), knowledgeAddDTO.getUserId(), knowledgeDataEntity.getId(), appendix.get(0));
            } else if (!Objects.equals(cabinetFileEntityList.get(0).getAttachIndex(), paasAttachmentEntityExt.getAttachIndex())) {
                cabinetFileModel.deleteByKey(cabinetFileEntityList.get(0).getId(), cabinetFileEntityList.get(0).getCorpid());
                insertCabinetFile(knowledgeAddDTO.getCorpid(), knowledgeAddDTO.getUserId(), knowledgeDataEntity.getId(), appendix.get(0));
            }
        }
        // 操作日志
        KnowledgeBaseEntity baseEntity = knowledgeBaseModel.getByKey(knowledgeAddDTO.getKnowledgeBaseId(), knowledgeAddDTO.getCorpid());
        String memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_EDIT_KNOWLEDGE_DATA), knowledgeAddDTO.getLoginUser().getName(), baseEntity.getKnowledgeName(), knowledgeAddDTO.getTitle());
        JSONObject newObj = JSONObject.parseObject(JSON.toJSONString(knowledgeDataEntity));
        JSONObject oldObj = JSONObject.parseObject(JSON.toJSONString(oldKnowledgeDataEntity));
        List<DetailLogPojo> detailArr = logHelp.getDetailArr4Normal(corpid, OperateModuleTypeEnum.KNOWLEDGE_BASE, oldObj, newObj);
        mongoLogHelp.buildLog4DetailArr(detailArr, corpid, knowledgeAddDTO.getLoginUser().getUserId(), knowledgeAddDTO.getLoginUser().getName(), OperateModuleTypeEnum.KNOWLEDGE_BASE, OperateTypeEnum.EDIT, knowledgeAddDTO.getId().toString(), knowledgeAddDTO.getTitle(), memo, knowledgeAddDTO.getHttpHeader());
        knowledgeVO.setId(knowledgeAddDTO.getId());
        return knowledgeVO;
    }

    @Override
    public FormDataDeleteBatchVO setupKnowledge(KnowledgeOperationDTO knowledgeOperationDTO) throws XbbException {
        FormDataDeleteBatchVO formDataDeleteBatchVO = new FormDataDeleteBatchVO();
        Map<String, Object> paramMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        paramMap.put("idIn", knowledgeOperationDTO.getIds());
        paramMap.put("knowledgeBaseId", knowledgeOperationDTO.getKnowledgeBaseId());
        paramMap.put("corpid", knowledgeOperationDTO.getCorpid());
        paramMap.put("del", 0);
        List<KnowledgeDataEntity> knowledgeDataEntities = knowledgeDataModel.findEntitys(paramMap);
        if (CollectionsUtil.isEmpty(knowledgeDataEntities)){
            throw new XbbException(KnowledgeErrorCodeEnum.API_ERROR_320017.getCode(), KnowledgeErrorCodeEnum.API_ERROR_320017.getMsg());
        }
        String corpid = knowledgeOperationDTO.getCorpid();
        List<InsertDTO> insertDTOList = new ArrayList<>();
        Map<String, Object> map = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        map.put(StringConstant.UPDATE_TIME, DateTimeUtil.getInt());
        map.put(KnowledgeDataEnum.STATUS.getAttr(), knowledgeOperationDTO.getEnable());
        map.put(KnowledgeDataEnum.UPDATE_ID.getAttr(), knowledgeOperationDTO.getUserId());
        for (KnowledgeDataEntity entity : knowledgeDataEntities) {
            InsertDTO insertDTO = new InsertDTO();
            insertDTO.setEsId(corpid + "_" + entity.getId());
            insertDTO.setIndexTypeEnum(IndexTypeEnum.IDX_SAAS_KNOWLEDGE_DATA);
            insertDTO.setIndex(IndexTypeEnum.IDX_SAAS_KNOWLEDGE_DATA.getIndex());
            insertDTO.setType(IndexTypeEnum.IDX_SAAS_KNOWLEDGE_DATA.getType());
            insertDTO.setSource(map);
            insertDTOList.add(insertDTO);
            entity.setStatus(knowledgeOperationDTO.getEnable());
            entity.setUpdateId(knowledgeOperationDTO.getUserId());
            entity.setUpdateTime(DateTimeUtil.getInt());
        }
        Integer success = knowledgeDataModel.updateBatch(knowledgeDataEntities, corpid);
        paasEsModel.updateBatch(insertDTOList);
        // 操作日志
        KnowledgeBaseEntity baseEntity = knowledgeBaseModel.getByKey(knowledgeOperationDTO.getKnowledgeBaseId(), knowledgeOperationDTO.getCorpid());
        for (KnowledgeDataEntity entity : knowledgeDataEntities) {
            if (Objects.equals(knowledgeOperationDTO.getEnable(), KnowledgeDataStatusEnum.ENABLE.getCode())) {
                String memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_ENABLE_KNOWLEDGE_DATA), knowledgeOperationDTO.getLoginUser().getName(), baseEntity.getKnowledgeName(), entity.getTitle());
                mongoLogHelp.buildLog4DetailArr(null, corpid, knowledgeOperationDTO.getLoginUser().getUserId(), knowledgeOperationDTO.getLoginUser().getName(), OperateModuleTypeEnum.KNOWLEDGE_BASE, OperateTypeEnum.SET, entity.getId().toString(), entity.getTitle(), memo, knowledgeOperationDTO.getHttpHeader());
            } else {
                String memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_DISABLE_KNOWLEDGE_DATA), knowledgeOperationDTO.getLoginUser().getName(), baseEntity.getKnowledgeName(), entity.getTitle());
                mongoLogHelp.buildLog4DetailArr(null, corpid, knowledgeOperationDTO.getLoginUser().getUserId(), knowledgeOperationDTO.getLoginUser().getName(), OperateModuleTypeEnum.KNOWLEDGE_BASE, OperateTypeEnum.SET, entity.getId().toString(), entity.getTitle(), memo, knowledgeOperationDTO.getHttpHeader());
            }
        }
        return formDataDeleteBatchVO;
    }

    @Override
    public PaasFormDataEsListVO listByEs(KnowledgeListDTO knowledgeListDTO) throws XbbException {
        PaasFormDataEsListVO formDataListVO;
        try {
            Integer businessType = knowledgeListDTO.getBusinessType();
            if (Objects.isNull(knowledgeListDTO.getPage()) || Objects.isNull(knowledgeListDTO.getPageSize())) {
                throw new XbbException(ThirdPartyUsageErrorCodeEnum.API_ERROR_900005, String.format(ThirdPartyUsageErrorCodeEnum.API_ERROR_900005.getMsg(), "分页参数"));
            }
            PaasFormExplainEntity paasFormExplainEntity = paasFormExplainModel.getByBusinessType(XbbRefTypeEnum.KNOWLEDGE_BASE.getCode(), "0");
            if (paasFormExplainEntity == null) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_EXPLAIN_NOT_EXIST);
            }
            //获取表单解释
            List<FieldAttrEntity> explainList = JSONArray.parseArray(paasFormExplainEntity.getExplains(), FieldAttrEntity.class);
            Iterator<? extends FieldAttrEntity> iterator = explainList.iterator();
            while (iterator.hasNext()) {
                FieldAttrEntity fieldAttrEntity = iterator.next();
                if (Objects.equals(fieldAttrEntity.getAttr(), KnowledgeDataEnum.TITLE.getAttr())) {
                    LinkDetailPojo linkDetailPojo = new LinkDetailPojo();
                    linkDetailPojo.setAttr(fieldAttrEntity.getAttr());
                    linkDetailPojo.setBusinessType(businessType);
                    linkDetailPojo.setSaasMark(SaasMarkEnum.SAAS.getCode());
                    linkDetailPojo.setSubBuisenssType(businessType);
                    fieldAttrEntity.setLinkDetail(linkDetailPojo);
                    continue;
                }
                if (Objects.equals(fieldAttrEntity.getAttr(), KnowledgeDataEnum.BASE_INFO.getAttr()) || Objects.equals(fieldAttrEntity.getAttr(), KnowledgeDataEnum.OTHER_INFO.getAttr())) {
                    iterator.remove();
                }
            }
            //数据查询
            formDataListVO = this.knowledgeList(knowledgeListDTO, explainList);
            //默认排序 字段显示
            FormDataListDTO formDataListDTO = new FormDataListDTO();
            BeanUtil.copyProperties(knowledgeListDTO, formDataListDTO);
            formDataListSearchHelp.setListColumn(formDataListDTO);
            formDataListVO.setUpdateTime(paasFormExplainEntity.getUpdateTime());
            formDataListVO.setHeadList(explainList);
            if (Objects.equals(knowledgeListDTO.getFromExport(), BasicConstant.ONE)) {
                return formDataListVO;
            }
            this.setButtons(formDataListDTO, formDataListVO);
        } catch (XbbException e) {
            LOG.error("错误信息", e);
            throw e;
        } catch (Exception e) {
            LOG.error("paasFormData数据库查询表单数据出错", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
        return formDataListVO;
    }

    /**
     * 获取知识条目列表按钮
     *
     * @param formDataListDTO
     * @param formDataListVO
     */
    private void setButtons(FormDataListDTO formDataListDTO, PaasFormDataEsListVO formDataListVO) throws XbbException {
        try {
            boolean isAdminOrBoss = formDataListDTO.getLoginUser().isAdminOrBoss();
            boolean permissionsBool=true;
            if (!isAdminOrBoss){
                KnowledgeBaseEntity baseEntity = knowledgeBaseModel.getByKey(formDataListDTO.getKnowledgeBaseId(), formDataListDTO.getCorpid());
                // 权限校验
                permissionsBool = knowledgeBaseHelp.permissionsValidation(formDataListDTO.getLoginUser(), baseEntity.getManagerConfig());
            }
            Integer subBusinessType = formDataListDTO.getSubBusinessType();
            List<ButtonPojo> topButtonList = new ArrayList<>();
            List<ButtonPojo> batchButtonList = new ArrayList<>();
            //获取顶部和底部按钮(提取)
            List<ListTopButtonEnum> topButtonEnumList = ListTopButtonEnum.getByBusinessType(subBusinessType);
            List<ListBatchEnum> bottomButtonEnumList = ListBatchEnum.getByBusinessType(subBusinessType);
            for (ListTopButtonEnum topButtonEnum : topButtonEnumList) {
                ButtonPojo buttonPojo = new ButtonPojo();
                BeanUtil.copyProperties(topButtonEnum.getAnEnum(), buttonPojo);
                buttonPojo.setDistributorMark(0);
                topButtonList.add(buttonPojo);
            }
            for (ListBatchEnum bottomButtonEnum : bottomButtonEnumList) {
                ButtonPojo buttonPojo = new ButtonPojo();
                BeanUtil.copyProperties(bottomButtonEnum.getAnEnum(), buttonPojo);
                buttonPojo.setDistributorMark(0);
                //塞入底部
                batchButtonList.add(buttonPojo);
            }
            if (permissionsBool) {
                formDataListVO.setTopPermissions(topButtonList);
                formDataListVO.setBottomPermissions(batchButtonList);
            }
        } catch (Exception e) {
            LOG.error("paasFormData.setButtons 出错", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
    }

    @Override
    public PaasFormDataEsListVO knowledgeList(KnowledgeListDTO knowledgeListDTO, List<FieldAttrEntity> explainList) throws XbbException {
        PaasFormDataEsListVO formDataListVO = new PaasFormDataEsListVO();
        try {
            String corpid = knowledgeListDTO.getCorpid();
            //分页
            Integer page = knowledgeListDTO.getPage();
            Integer pageSize = knowledgeListDTO.getPageSize();
            Long knowledgeBaseId = knowledgeListDTO.getKnowledgeBaseId();
            SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
            BoolQueryBuilder boolQueryBuilder = boolQuery();
            boolQueryBuilder.filter(termQuery("corpid.keyword", corpid));
            boolQueryBuilder.filter(termQuery("knowledgeBaseId", knowledgeBaseId));
            boolean isAdminOrBoss = knowledgeListDTO.getLoginUser().isAdminOrBoss();
            if (Objects.nonNull(knowledgeListDTO.getCatalogueId())) {
                // 查询出所有的子目录id
                List<Long> allCatalogueIdList = new ArrayList<>();
                allCatalogueIdList.add(knowledgeListDTO.getCatalogueId());
                knowledgeBaseHelp.getAllChildCatalogueId(corpid, knowledgeBaseId, allCatalogueIdList);
                boolQueryBuilder.filter(termsQuery("catalogueId", allCatalogueIdList));
            } else {
                if (!isAdminOrBoss) {
                    List<Long> catalogueIdList = knowledgeBaseHelp.getCatalogueIdList(corpid, knowledgeBaseId, knowledgeListDTO.getLoginUser());
                    if (CollectionsUtil.isNotEmpty(catalogueIdList)) {
                        boolQueryBuilder.filter(termsQuery("catalogueId", catalogueIdList));
                    } else {
                        PageHelper pageHelper = new PageHelper(page, pageSize);
                        pageHelper.setRowsCount(0);
                        formDataListVO.setPaasFormDataESList(new ArrayList<>());
                        formDataListVO.setPageHelper(pageHelper);
                        formDataListVO.setBusinessType(knowledgeListDTO.getBusinessType());
                        return formDataListVO;
                    }
                }
            }
            if (CollectionsUtil.isNotEmpty(knowledgeListDTO.getIdIn())) {
                boolQueryBuilder.filter(termsQuery("id", knowledgeListDTO.getIdIn()));
            }
            if (Objects.nonNull(knowledgeListDTO.getStatus())) {
                boolQueryBuilder.filter(termQuery(KnowledgeDataEnum.STATUS.getAttr(), knowledgeListDTO.getStatus()));
            }
            if (CollectionsUtil.isNotEmpty(knowledgeListDTO.getTags())) {
                boolQueryBuilder.filter(termsQuery(KnowledgeDataEnum.LABEL.getAttr(), knowledgeListDTO.getTags()));
            }
            boolQueryBuilder.filter(termQuery("del", 0));
            boolQueryBuilder.filter(termQuery(ElasticConstant.MY_JOIN_FIELD, IndexTypeEnum.IDX_SAAS_KNOWLEDGE_DATA.getType()));
            //输入框搜索
            if (StringUtil.isNotEmpty(knowledgeListDTO.getNameLike())) {
                boolQueryBuilder.filter(matchPhraseQuery(KnowledgeDataEnum.TITLE.getAttr(), knowledgeListDTO.getNameLike()));
            }
            if (Objects.equals(2, knowledgeListDTO.getFromExport()) && Objects.nonNull(knowledgeListDTO.getSearchAfterList()) && knowledgeListDTO.getSearchAfterList().length>0) {
                // 导出数据的游标
                sourceBuilder.searchAfter(knowledgeListDTO.getSearchAfterList());
            }
            sourceBuilder.query(boolQueryBuilder);
            SearchRequest searchRequest = new SearchRequest(IndexTypeEnum.IDX_SAAS_KNOWLEDGE_DATA.getIndex());
            searchRequest.source(sourceBuilder);
            //解析查询条件
            EsUtil.parseCondition(boolQueryBuilder, knowledgeListDTO.getConditions(), "", knowledgeListDTO.getCorpid(), XbbRefTypeEnum.KNOWLEDGE_BASE.getCode());
            //排序
            SortOrder order = SortOrder.DESC;
            String sortField = "updateTime";
            Map<String, String> sortMap = knowledgeListDTO.getSortMap();
            if (sortMap != null && !sortMap.isEmpty()) {
                sortField = (StringUtil.isEmpty(sortMap.get("field")) ? sortField : sortMap.get("field"));
                Map<String, FieldAttrEntity> explainMap = new HashMap<>(explainList.size());
                explainList.forEach(item -> {
                    explainMap.put(item.getAttr(), item);
                });
                if (explainMap.containsKey(sortField)) {
                    String raw = ".raw";
                    FieldAttrEntity sortFieldEntity = explainMap.get(sortField);
                    FieldTypeEnum fieldTypeEnum = FieldTypeEnum.getFieldTypeEnum(sortFieldEntity.getFieldType());
                    if (FieldTypeEnum.TEXT.getEsalias().equals(fieldTypeEnum.getEsalias())) {
                        sortField = sortField + raw;
                    }
                } else {
                    // 排序不存在字段列表中时，给定默认排序，以防报错
                    sortField = "updateTime";
                }
                if (SortOrder.ASC.toString().equals(sortMap.get("sort"))) {
                    order = SortOrder.ASC;
                }
            }
            sourceBuilder.sort(new FieldSortBuilder(sortField).order(order));
            PageRequest pageRequest = EsUtil.setPage(sourceBuilder, page, pageSize);
            String prefix = "------------------listByEs------------------:";
            long num;
            List<KnowledgeEsAddDTO> knowledgeEsDataVo;
            List<PaasFormDataEntityExt> paasFormDataESList = new ArrayList<>();
            XbbAggregatedPage<KnowledgeEsAddDTO> esEntities = xbbElasticsearchRestTemplate.queryForPages(pageRequest, searchRequest, KnowledgeEsAddDTO.class);
            num = esEntities.getTotalElements();
            knowledgeEsDataVo = esEntities.getContent();
            if (esEntities == null) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
            }
            Set<String> creatorIds = new HashSet<>();
            //获取标签名称
            Set<Long> tagIds = new HashSet<>();
            List<Long> ids = new ArrayList<>();
            for (KnowledgeEsAddDTO knowledgeEsAddDTO : knowledgeEsDataVo) {
                creatorIds.add(knowledgeEsAddDTO.getCreatorId());
                creatorIds.add(knowledgeEsAddDTO.getUpdateId());
                ids.add(knowledgeEsAddDTO.getId());
                if (CollectionsUtil.isNotEmpty(knowledgeEsAddDTO.getLabel())) {
                    tagIds.addAll(knowledgeEsAddDTO.getLabel());
                }
            }
            Map<String, Object> paramMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            paramMap.put("corpid", corpid);
            paramMap.put("del", 0);
            paramMap.put("idIn", ids);
            List<KnowledgeDataEntity> knowledgeDataEntities = knowledgeDataModel.findEntitys(paramMap);
            Map<Long, KnowledgeDataEntity> KnowledgeEntitieMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            for (KnowledgeDataEntity knowledgeDataEntity : knowledgeDataEntities) {
                KnowledgeEntitieMap.put(knowledgeDataEntity.getId(), knowledgeDataEntity);
            }
            Map<Long, KnowledgeTagEntity> KnowledgeTagMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            if (tagIds.size() > 0) {
                List<Long> labIds = new ArrayList<Long>(tagIds);
                paramMap.clear();
                paramMap.put("corpid", corpid);
                paramMap.put("del", 0);
                paramMap.put("idIn", labIds);
                List<KnowledgeTagEntity> knowledgeTagEntities = knowledgeTagModel.findEntitys(paramMap);
                for (KnowledgeTagEntity knowledgeTagEntity : knowledgeTagEntities) {
                    KnowledgeTagMap.put(knowledgeTagEntity.getId(), knowledgeTagEntity);
                }
            }
            List<UserEntity> userEntities = userModel.findEntitysByUserIds(new ArrayList<String>(creatorIds), knowledgeListDTO.getCorpid());
            Map<String, String> userIdAndNameMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            for (UserEntity entity : userEntities) {
                userIdAndNameMap.put(entity.getUserId(), entity.getName());
            }
            //获取目录ID
            List<Long> catalogueIds = knowledgeEsDataVo.stream().map(KnowledgeEsAddDTO::getCatalogueId).collect(Collectors.toList()).stream().distinct().collect(Collectors.toList());
            paramMap.clear();
            paramMap.put("columns", "id,name");
            paramMap.put("corpid", corpid);
            paramMap.put("del", 0);
            paramMap.put("idIn", catalogueIds);
            List<KnowledgeCatalogueEntity> knowledgeCatalogueEntities = knowledgeCatalogueModel.findEntitys(paramMap);
            Map<Long, String> catalogueIdAndNameMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            for (KnowledgeCatalogueEntity entity : knowledgeCatalogueEntities) {
                catalogueIdAndNameMap.put(entity.getId(), entity.getName());
            }
            for (KnowledgeEsAddDTO knowledgeEsAddDTO : knowledgeEsDataVo) {
                PaasFormDataEntityExt paasFormDataEntityExt = new PaasFormDataEntityExt();
                paasFormDataEntityExt.setCorpid(knowledgeEsAddDTO.getCorpid());
                //附件转换
                String appendixStr = knowledgeEsAddDTO.getAppendix();
                paasFormDataEntityExt.setData(JSONObject.parseObject(JSONObject.toJSONString(knowledgeEsAddDTO)));
                if (StringUtil.isNotEmpty(appendixStr)) {
                    List<PaasAttachmentEntityExt> appendix = JSONArray.parseArray(appendixStr, PaasAttachmentEntityExt.class);
                    paasFormDataEntityExt.getData().put(KnowledgeDataEnum.APPENDIX.getAttr(), appendix);
                }
                if (CollectionsUtil.isNotEmpty(knowledgeEsAddDTO.getKeywords())) {
                    String keyword = Joiner.on("、").join(knowledgeEsAddDTO.getKeywords());
                    paasFormDataEntityExt.getData().put(KnowledgeDataEnum.KEYWORDS.getAttr(), keyword);
                } else {
                    paasFormDataEntityExt.getData().put(KnowledgeDataEnum.KEYWORDS.getAttr(), "");
                }
                if (CollectionsUtil.isNotEmpty(knowledgeEsAddDTO.getExpandConsult())) {
                    String expandConsult = Joiner.on("、").join(knowledgeEsAddDTO.getExpandConsult());
                    paasFormDataEntityExt.getData().put(KnowledgeDataEnum.EXPAND_CONSULT.getAttr(), expandConsult);
                } else {
                    paasFormDataEntityExt.getData().put(KnowledgeDataEnum.EXPAND_CONSULT.getAttr(), "");
                }
                // 标签
                JSONArray tags = new JSONArray();
                StringJoiner tagString = new StringJoiner(",");
                if (CollectionsUtil.isNotEmpty(knowledgeEsAddDTO.getLabel())) {
                    for (Long tagId : knowledgeEsAddDTO.getLabel()) {
                        JSONObject object = new JSONObject();
                        KnowledgeTagEntity knowledgeTagEntity = KnowledgeTagMap.get(tagId);
                        if (Objects.nonNull(knowledgeTagEntity)) {
                            object.put("id", knowledgeTagEntity.getId());
                            object.put("name", knowledgeTagEntity.getName());
                            object.put("parentTagId", knowledgeTagEntity.getParentId());
                            object.put("color", knowledgeTagEntity.getColor());
                            tagString.add(knowledgeTagEntity.getName());
                            tags.add(object);
                        }
                    }
                }
                KnowledgeDataEntity knowledgeDataEntity = KnowledgeEntitieMap.get(knowledgeEsAddDTO.getId());
                paasFormDataEntityExt.getData().put(KnowledgeDataEnum.LABEL.getAttr(), tags);
                if (Objects.isNull(knowledgeListDTO.getFromExport()) || Objects.equals(knowledgeListDTO.getFromExport(), 0)) {
                    if (Objects.nonNull(knowledgeDataEntity)) {
                        List<KnowledgeContentDTO> knowledgeContentDTOS = JSONArray.parseArray(knowledgeDataEntity.getContentArray(), KnowledgeContentDTO.class);
                        for (KnowledgeContentDTO knowledgeContentDTO : knowledgeContentDTOS) {
                            if (Objects.equals(knowledgeContentDTO.getType(), KnowledgeContentTypeEnum.TEXT.getCode())) {
                                String content = knowledgeContentDTO.getContent();
                                if (StringUtil.isNotEmpty(content) && StringUtil.isNotEmpty(content.trim())) {
                                    content = content.replaceAll("&nbsp;", "");
                                    knowledgeContentDTO.setContent(knowledgeBaseHelp.cleanHtmlTag(content));
                                }
                            }
                        }
                        paasFormDataEntityExt.getData().put(KnowledgeDataEnum.CONTENT.getAttr(), knowledgeContentDTOS);
                    }
                } else {
                    paasFormDataEntityExt.getData().put(KnowledgeDataEnum.UPDATE_TIME.getAttr(), DateTimeUtil.getString(knowledgeEsAddDTO.getUpdateTime().intValue(), DateTimeUtil.SDF));
                    paasFormDataEntityExt.getData().put(KnowledgeDataEnum.ADD_TIME.getAttr(), DateTimeUtil.getString(knowledgeEsAddDTO.getAddTime().intValue(), DateTimeUtil.SDF));
                    //paasFormDataEntityExt.getData().put(KnowledgeDataEnum.LABEL.getAttr(), tagString.toString());
                }
                paasFormDataEntityExt.getData().put(KnowledgeDataEnum.CREATOR_ID.getAttr(), userIdAndNameMap.get(knowledgeEsAddDTO.getCreatorId()));
                paasFormDataEntityExt.getData().put(KnowledgeDataEnum.UPDATE_ID.getAttr(), userIdAndNameMap.get(knowledgeEsAddDTO.getUpdateId()));
                paasFormDataEntityExt.getData().put(KnowledgeDataEnum.CATALOGUE.getAttr(), catalogueIdAndNameMap.get(knowledgeEsAddDTO.getCatalogueId()));
                paasFormDataEntityExt.getData().put(KnowledgeDataEnum.STATUS.getAttr(), KnowledgeDataStatusEnum.getByCode(knowledgeEsAddDTO.getStatus()));
                paasFormDataEntityExt.setCorpid(knowledgeEsAddDTO.getCorpid());
                paasFormDataEntityExt.setDataId(knowledgeEsAddDTO.getDataId());
                paasFormDataEntityExt.setId(knowledgeEsAddDTO.getId());
                paasFormDataEntityExt.setCreatorId(userIdAndNameMap.get(knowledgeEsAddDTO.getCreatorId()));
                paasFormDataESList.add(paasFormDataEntityExt);
            }
            PageHelper pageHelper = new PageHelper(page, pageSize);
            pageHelper.setRowsCount((int) num);
            formDataListVO.setPaasFormDataESList(paasFormDataESList);
            formDataListVO.setSortValue(esEntities.getSortValue());
            formDataListVO.setPageHelper(pageHelper);
            formDataListVO.setBusinessType(knowledgeListDTO.getBusinessType());
        } catch (Exception e) {
            LOG.error("es查询出错", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
        return formDataListVO;
    }

    @Override
    public ListAppVO appKnowledgeDataList(KnowledgeListDTO knowledgeListDTO) throws XbbException {
        ListAppVO listAppVO = new ListAppVO();
        try {
            String corpid = knowledgeListDTO.getCorpid();
            //分页
            Integer page = knowledgeListDTO.getPage();
            Integer pageSize = knowledgeListDTO.getPageSize();
            Long knowledgeBaseId = knowledgeListDTO.getKnowledgeBaseId();
            //获取表单解释
            PaasFormExplainEntity paasFormExplainEntity = paasFormExplainModel.getByBusinessType(XbbRefTypeEnum.KNOWLEDGE_BASE.getCode(), "0");
            if (paasFormExplainEntity == null) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_EXPLAIN_NOT_EXIST);
            }
            List<FieldAttrEntity> explainList = JSONArray.parseArray(paasFormExplainEntity.getExplains(), FieldAttrEntity.class);
            List<AppListPojo> appListPojos = new ArrayList<>();
            SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
            BoolQueryBuilder boolQueryBuilder = boolQuery();
            boolQueryBuilder.filter(termQuery("corpid.keyword", corpid));
            boolQueryBuilder.filter(termQuery("knowledgeBaseId", knowledgeBaseId));
            boolean isAdminOrBoss = knowledgeListDTO.getLoginUser().isAdminOrBoss();
            if (Objects.nonNull(knowledgeListDTO.getCatalogueId())) {
                // 查询出所有的子目录id
                List<Long> allCatalogueIdList = new ArrayList<>();
                allCatalogueIdList.add(knowledgeListDTO.getCatalogueId());
                knowledgeBaseHelp.getAllChildCatalogueId(corpid, knowledgeBaseId, allCatalogueIdList);
                boolQueryBuilder.filter(termsQuery("catalogueId", allCatalogueIdList));
            } else {
                if (!isAdminOrBoss) {
                    List<Long> catalogueIdList = knowledgeBaseHelp.getCatalogueIdList(corpid, knowledgeBaseId, knowledgeListDTO.getLoginUser());
                    if (CollectionsUtil.isNotEmpty(catalogueIdList)) {
                        boolQueryBuilder.filter(termsQuery("catalogueId", catalogueIdList));
                    } else {
                        PageHelper pageHelper = new PageHelper(page, pageSize);
                        pageHelper.setRowsCount(0);
                        listAppVO.setList(appListPojos);
                        listAppVO.setPageHelper(pageHelper);
                        return listAppVO;
                    }
                }
            }
            boolQueryBuilder.filter(termQuery("del", 0));
            boolQueryBuilder.filter(termQuery(ElasticConstant.MY_JOIN_FIELD, IndexTypeEnum.IDX_SAAS_KNOWLEDGE_DATA.getType()));
            //输入框搜索
            if (StringUtil.isNotEmpty(knowledgeListDTO.getNameLike())) {
                boolQueryBuilder.filter(matchPhraseQuery(KnowledgeDataEnum.TITLE.getAttr(), knowledgeListDTO.getNameLike()));
            }
            sourceBuilder.query(boolQueryBuilder);
            SearchRequest searchRequest = new SearchRequest(IndexTypeEnum.IDX_SAAS_KNOWLEDGE_DATA.getIndex());
            searchRequest.source(sourceBuilder);
            //解析查询条件
            EsUtil.parseCondition(boolQueryBuilder, knowledgeListDTO.getConditions(), "", knowledgeListDTO.getCorpid(), XbbRefTypeEnum.KNOWLEDGE_BASE.getCode());
            //排序
            SortOrder order = SortOrder.DESC;
            String sortField = "updateTime";
            Map<String, String> sortMap = knowledgeListDTO.getSortMap();
            if (sortMap != null && !sortMap.isEmpty()) {
                sortField = (StringUtil.isEmpty(sortMap.get("field")) ? sortField : sortMap.get("field"));
                Map<String, FieldAttrEntity> explainMap = new HashMap<>(explainList.size());
                explainList.forEach(item -> {
                    explainMap.put(item.getAttr(), item);
                });
                if (explainMap.containsKey(sortField)) {
                    String raw = ".raw";
                    FieldAttrEntity sortFieldEntity = explainMap.get(sortField);
                    FieldTypeEnum fieldTypeEnum = FieldTypeEnum.getFieldTypeEnum(sortFieldEntity.getFieldType());
                    if (FieldTypeEnum.TEXT.getEsalias().equals(fieldTypeEnum.getEsalias())) {
                        sortField = sortField + raw;
                    }
                } else {
                    // 排序不存在字段列表中时，给定默认排序，以防报错
                    sortField = "updateTime";
                }
                if (SortOrder.ASC.toString().equals(sortMap.get("sort"))) {
                    order = SortOrder.ASC;
                }
            }
            sourceBuilder.sort(new FieldSortBuilder(sortField).order(order));
            PageRequest pageRequest = EsUtil.setPage(sourceBuilder, page, pageSize);
            long num;
            List<KnowledgeEsAddDTO> knowledgeEsDataVo;
            XbbAggregatedPage<KnowledgeEsAddDTO> esEntities = xbbElasticsearchRestTemplate.queryForPages(pageRequest, searchRequest, KnowledgeEsAddDTO.class);
            if (esEntities == null) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
            }
            knowledgeEsDataVo = esEntities.getContent();
            //获取标签名称
            Set<Long> tagIds = new HashSet<>();
            List<Long> ids = new ArrayList<>();
            for (KnowledgeEsAddDTO knowledgeEsAddDTO : knowledgeEsDataVo) {
                if (CollectionsUtil.isNotEmpty(knowledgeEsAddDTO.getLabel())) {
                    tagIds.addAll(knowledgeEsAddDTO.getLabel());
                }
                ids.add(knowledgeEsAddDTO.getId());
            }
            Map<String, Object> paramMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            paramMap.put("corpid", corpid);
            paramMap.put("del", 0);
            paramMap.put("idIn", ids);
            List<KnowledgeDataEntity> knowledgeDataEntities = knowledgeDataModel.findEntitys(paramMap);
            Map<Long, KnowledgeDataEntity> KnowledgeEntitieMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            for (KnowledgeDataEntity knowledgeDataEntity : knowledgeDataEntities) {
                KnowledgeEntitieMap.put(knowledgeDataEntity.getId(), knowledgeDataEntity);
            }
            Map<Long, KnowledgeTagEntity> KnowledgeTagMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            if (tagIds.size() > 0) {
                List<Long> labIds = new ArrayList<>(tagIds);
                paramMap.clear();
                paramMap.put("corpid", corpid);
                paramMap.put("del", 0);
                paramMap.put("idIn", labIds);
                List<KnowledgeTagEntity> knowledgeTagEntities = knowledgeTagModel.findEntitys(paramMap);
                for (KnowledgeTagEntity knowledgeTagEntity : knowledgeTagEntities) {
                    KnowledgeTagMap.put(knowledgeTagEntity.getId(), knowledgeTagEntity);
                }
            }
            for (KnowledgeEsAddDTO knowledgeEsAddDTO : knowledgeEsDataVo) {
                JSONArray explains = new JSONArray();
                JSONObject others = new JSONObject();
                others.put(StringConstant.BUSINESS_TYPE, XbbRefTypeEnum.KNOWLEDGE_BASE.getCode());
                others.put(StringConstant.DATA_ID, knowledgeEsAddDTO.getId());
                others.put(KnowledgeDataEnum.TITLE.getAttr(), knowledgeEsAddDTO.getTitle());
                if (CollectionsUtil.isNotEmpty(knowledgeEsAddDTO.getKeywords())) {
                    String keyword = Joiner.on("、").join(knowledgeEsAddDTO.getKeywords());
                    others.put(KnowledgeDataEnum.KEYWORDS.getAttr(), keyword);
                } else {
                    others.put(KnowledgeDataEnum.KEYWORDS.getAttr(), "");
                }
                KnowledgeDataEntity knowledgeDataEntity = KnowledgeEntitieMap.get(knowledgeEsAddDTO.getId());
                if (Objects.nonNull(knowledgeDataEntity)) {
                    List<KnowledgeContentDTO> knowledgeContentDTOS = JSONArray.parseArray(knowledgeDataEntity.getContentArray(), KnowledgeContentDTO.class);
                    for (KnowledgeContentDTO knowledgeContentDTO : knowledgeContentDTOS) {
                        if (Objects.equals(knowledgeContentDTO.getType(), KnowledgeContentTypeEnum.TEXT.getCode())) {
                            String content = knowledgeContentDTO.getContent();
                            if (StringUtil.isNotEmpty(content) && StringUtil.isNotEmpty(content.trim())) {
                                content = content.replaceAll("&nbsp;", "");
                                knowledgeContentDTO.setContent(knowledgeBaseHelp.cleanHtmlTag(content));
                            }
                        }
                    }
                    others.put(KnowledgeDataEnum.CONTENT.getAttr(), knowledgeContentDTOS);
                } else {
                    others.put(KnowledgeDataEnum.CONTENT.getAttr(), new JSONArray());
                }
                others.put(KnowledgeDataEnum.USAGE_COUNT.getAttr(), knowledgeEsAddDTO.getUsageCount());
                others.put(KnowledgeDataEnum.STATUS.getAttr(), knowledgeEsAddDTO.getStatus());
                // 标签
                JSONArray tags = new JSONArray();
                if (CollectionsUtil.isNotEmpty(knowledgeEsAddDTO.getLabel())) {
                    for (Long tagId : knowledgeEsAddDTO.getLabel()) {
                        JSONObject object = new JSONObject();
                        KnowledgeTagEntity knowledgeTagEntity = KnowledgeTagMap.get(tagId);
                        if (Objects.nonNull(knowledgeTagEntity)) {
                            object.put("id", knowledgeTagEntity.getId());
                            object.put("name", knowledgeTagEntity.getName());
                            object.put("parentTagId", knowledgeTagEntity.getParentId());
                            object.put("color", knowledgeTagEntity.getColor());
                            tags.add(object);
                        }
                    }
                }
                others.put(KnowledgeDataEnum.LABEL.getAttr(), tags);
                appListPojos.add(new AppListPojo(knowledgeEsAddDTO.getId(), knowledgeEsAddDTO.getTitle(), explains, null, null, others));
            }
            num = esEntities.getTotalElements();
            listAppVO.setList(appListPojos);
            PageHelper pageHelper = new PageHelper(page, pageSize);
            pageHelper.setRowsCount((int) num);
            listAppVO.setPageHelper(pageHelper);
        } catch (Exception e) {
            LOG.error("es查询出错", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
        return listAppVO;
    }

    @Override
    public FormDataDetailVO getWebDetail(FormDataDetailDTO formDataDetailDTO) throws XbbException {
        FormDataDetailVO formDataDetailVO = new FormDataDetailVO();
        Long id = formDataDetailDTO.getDataId();
        String corpid = formDataDetailDTO.getCorpid();
        Integer businessType = formDataDetailDTO.getBusinessType();
        KnowledgeDataEntity knowledgeDataEntity = knowledgeDataModel.getByKey(id, corpid);
        if (Objects.isNull(knowledgeDataEntity)){
            throw new XbbException(KnowledgeErrorCodeEnum.API_ERROR_320017.getCode(),KnowledgeErrorCodeEnum.API_ERROR_320017.getMsg());
        }
        List<DetailTabPojo> tabPojoList = new ArrayList<>();
        // saas详情tab
        DataDetailPojo dataDetailPojo = new DataDetailPojo();
        List<ButtonPojo> buttonPojoList = new ArrayList<>();
        //tab处理
        List<BusinessDetailTabEnum> tabEnumList = BusinessDetailTabEnum.getByBusinessType(businessType);
        for (BusinessDetailTabEnum tabEnum : tabEnumList) {
            DetailTabPojo detailTabPojo = new DetailTabPojo();
            BeanUtil.copyProperties(tabEnum.getAnEnum(), detailTabPojo);
            detailTabPojo.setAttr(detailTabPojo.getKey());
            tabPojoList.add(detailTabPojo);
        }
        Integer status = knowledgeDataEntity.getStatus();
        //button处理
        boolean isAdminOrBoss = formDataDetailDTO.getLoginUser().isAdminOrBoss();
        boolean permissionsBool=true;
        if (!isAdminOrBoss){
            KnowledgeBaseEntity baseEntity = knowledgeBaseModel.getByKey(formDataDetailDTO.getKnowledgeBaseId(), formDataDetailDTO.getCorpid());
            // 权限校验
            permissionsBool = knowledgeBaseHelp.permissionsValidation(formDataDetailDTO.getLoginUser(), baseEntity.getManagerConfig());
        }
        if (permissionsBool) {
            List<BusinessDetailButtonEnum> buttonEnumList = BusinessDetailButtonEnum.getByBusinessType(businessType);
            for (BusinessDetailButtonEnum buttonEnum : buttonEnumList) {
                ButtonPojo buttonPojo = new ButtonPojo();
                SaasButtonEnum saasButtonEnum = buttonEnum.getAnEnum();
                BeanUtil.copyProperties(saasButtonEnum, buttonPojo);
                buttonPojo.setLinkBusinessType(buttonEnum.getLinkBusinessType());
                if (Objects.equals(status, KnowledgeDataStatusEnum.ENABLE.getCode()) && (Objects.equals(buttonEnum, BusinessDetailButtonEnum.KNOWLEDGE_DATA_ENABLE))) {
                    buttonPojo.setValue(SaasButtonEnum.DISENABLE.getValue());
                    buttonPojo.setAttr(KnowledgeDataStatusEnum.BLOCK_UP.getAttr());
                }
                buttonPojoList.add(buttonPojo);
            }
        }
        // 详情标签、摘要(按顺序返回给前端)
        // 标签
        JSONArray tags = new JSONArray();
        if (Objects.nonNull(knowledgeDataEntity.getLabel()) && CollectionsUtil.isNotEmpty(JSONArray.parseArray(knowledgeDataEntity.getLabel(), String.class))) {
            Map<String, Object> paramMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            paramMap.put("corpid", corpid);
            paramMap.put("del", 0);
            paramMap.put("idIn", JSONArray.parseArray(knowledgeDataEntity.getLabel(), String.class));
            List<KnowledgeTagEntity> knowledgeTagEntities = knowledgeTagModel.findEntitys(paramMap);
            for (KnowledgeTagEntity knowledgeTagEntity : knowledgeTagEntities) {
                if (Objects.nonNull(knowledgeTagEntity)) {
                    JSONObject object = new JSONObject();
                    object.put("type", "label");
                    JSONObject tag= new JSONObject();
                    tag.put("name", knowledgeTagEntity.getName());
                    tag.put("id", knowledgeTagEntity.getId());
                    tag.put("color", knowledgeTagEntity.getColor());
                    object.put("value",tag);
                    tags.add(object);
                }
            }
        }
        JSONArray secondTitle = new JSONArray();
        UserEntity userEntity = userModel.getByKey(knowledgeDataEntity.getCreatorId(), corpid);
        String creatorName = "";
        if (Objects.nonNull(userEntity)) {
            creatorName = userEntity.getName();
        }
        JSONObject creatorTitleObj = ExplainUtil.getSecondTitleObj(false, KnowledgeDataEnum.CREATOR_ID.getAttrName(), creatorName);
        JSONObject statusTitleObj = ExplainUtil.getSecondTitleObj(false, KnowledgeDataEnum.STATUS.getAttrName(), KnowledgeDataStatusEnum.getByCode(status));
        secondTitle.add(creatorTitleObj);
        secondTitle.add(statusTitleObj);
        DetailTitlePojo detailTitlePojo = new DetailTitlePojo();
        detailTitlePojo.setName(knowledgeDataEntity.getTitle());
        //不支持排序
        dataDetailPojo.setTabSortPermission(false);
        dataDetailPojo.setButton(buttonPojoList);
        dataDetailPojo.setTitle(detailTitlePojo);
        dataDetailPojo.setSecondTitle(secondTitle);
        dataDetailPojo.setTags(tags);
        formDataDetailVO.setHead(dataDetailPojo);
        PaasFormEntityExt paasFormEntityExt=new PaasFormEntityExt();
        paasFormEntityExt.setId(0L);
        formDataDetailVO.setPaasFormEntityExt(paasFormEntityExt);
        formDataDetailVO.setTab(tabPojoList);
        return formDataDetailVO;
    }

    @Override
    public FormDataGetVO get(FormDataGetDTO formDataGetDTO) throws XbbException {
        FormDataGetVO formDataGetVO = new FormDataGetVO();
        try {
            Long id = formDataGetDTO.getDataId();
            String corpid = formDataGetDTO.getCorpid();
            Integer businessType = formDataGetDTO.getBusinessType();
            KnowledgeDataEntity knowledgeDataEntity = knowledgeDataModel.getByKey(id, corpid);
            if (Objects.isNull(knowledgeDataEntity)){
                throw new XbbException(KnowledgeErrorCodeEnum.API_ERROR_320017.getCode(),KnowledgeErrorCodeEnum.API_ERROR_320017.getMsg());
            }
            List<String> userIds = new ArrayList<>();
            userIds.add(knowledgeDataEntity.getCreatorId());
            userIds.add(knowledgeDataEntity.getUpdateId());
            List<UserEntity> userEntitys = userModel.findEntitysByUserIds(userIds, corpid);
            Map<String, String> userIdAndNameMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            for (UserEntity entity : userEntitys) {
                userIdAndNameMap.put(entity.getUserId(), entity.getName());
            }
            //获取表单解释
            PaasFormExplainEntity paasFormExplainEntity = paasFormExplainModel.getByBusinessType(businessType, "0");
            if (paasFormExplainEntity == null) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_EXPLAIN_NOT_EXIST);
            }
            List<FieldAttrEntity> explainList = JSONArray.parseArray(paasFormExplainEntity.getExplains(), FieldAttrEntity.class);
            //获取目录
            KnowledgeCatalogueEntity knowledgeCatalogueEntity = knowledgeCatalogueModel.getByKey(knowledgeDataEntity.getCatalogueId(), corpid);
            //formList数据组装
            PaasFormDataEntityExt paasFormDataEntityExt = new PaasFormDataEntityExt();
            paasFormDataEntityExt.setId(knowledgeDataEntity.getId());
            paasFormDataEntityExt.setDataId(knowledgeDataEntity.getId());
            paasFormDataEntityExt.setCorpid(knowledgeDataEntity.getCorpid());
            paasFormDataEntityExt.setBusinessType(businessType);
            JSONObject data = JSONObject.parseObject(JSONObject.toJSONString(knowledgeDataEntity));
            if (Objects.nonNull(knowledgeDataEntity.getKeywords()) && CollectionsUtil.isNotEmpty(JSONArray.parseArray(knowledgeDataEntity.getKeywords(), String.class))) {
                String keyword = Joiner.on("、").join(JSONArray.parseArray(knowledgeDataEntity.getKeywords(), String.class));
                data.put(KnowledgeDataEnum.KEYWORDS.getAttr(), keyword);
            } else {
                data.put(KnowledgeDataEnum.KEYWORDS.getAttr(), "");
            }
            if (Objects.nonNull(knowledgeDataEntity.getExpandConsult()) && CollectionsUtil.isNotEmpty(JSONArray.parseArray(knowledgeDataEntity.getExpandConsult(), String.class))) {
                String expandConsult = Joiner.on("、").join(JSONArray.parseArray(knowledgeDataEntity.getExpandConsult(), String.class));
                data.put(KnowledgeDataEnum.EXPAND_CONSULT.getAttr(), expandConsult);
            } else {
                data.put(KnowledgeDataEnum.EXPAND_CONSULT.getAttr(), "");
            }
            String appendixStr = knowledgeDataEntity.getAppendix();
            if (StringUtil.isNotEmpty(appendixStr)) {
                List<PaasAttachmentEntityExt> appendix = JSONArray.parseArray(appendixStr, PaasAttachmentEntityExt.class);
                data.put(KnowledgeDataEnum.APPENDIX.getAttr(), appendix);
            }
            // 标签
            JSONArray tags = new JSONArray();
            if (Objects.nonNull(knowledgeDataEntity.getLabel()) && CollectionsUtil.isNotEmpty(JSONArray.parseArray(knowledgeDataEntity.getLabel(), String.class))) {
                Map<String, Object> paramMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                paramMap.put("corpid", corpid);
                paramMap.put("del", 0);
                paramMap.put("idIn", JSONArray.parseArray(knowledgeDataEntity.getLabel(), String.class));
                List<KnowledgeTagEntity> knowledgeTagEntities = knowledgeTagModel.findEntitys(paramMap);
                for (KnowledgeTagEntity knowledgeTagEntity : knowledgeTagEntities) {
                    JSONObject object = new JSONObject();
                    if (Objects.nonNull(knowledgeTagEntity)) {
                        object.put("id", knowledgeTagEntity.getId());
                        object.put("name", knowledgeTagEntity.getName());
                        object.put("parentTagId", knowledgeTagEntity.getParentId());
                        object.put("color", knowledgeTagEntity.getColor());
                        tags.add(object);
                    }
                }
            }
            data.put(KnowledgeDataEnum.CONTENT.getAttr(), JSONArray.parseArray(knowledgeDataEntity.getContentArray(), KnowledgeContentDTO.class));
            data.put(KnowledgeDataEnum.LABEL.getAttr(), tags);
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("id", knowledgeDataEntity.getCreatorId());
            jsonObject.put("name", userIdAndNameMap.get(knowledgeDataEntity.getCreatorId()));
            data.put(KnowledgeDataEnum.CREATOR_ID.getAttr(), jsonObject);
            data.put(KnowledgeDataEnum.UPDATE_ID.getAttr(), userIdAndNameMap.get(knowledgeDataEntity.getUpdateId()));
            data.put(KnowledgeDataEnum.CATALOGUE.getAttr(), knowledgeCatalogueEntity.getName());
            data.put(KnowledgeDataEnum.STATUS.getAttr(), KnowledgeDataStatusEnum.getByCode(knowledgeDataEntity.getStatus()));
            paasFormDataEntityExt.setData(data);
            paasFormDataEntityExt.setId(0L);
            formDataGetVO.setFormList(paasFormDataEntityExt);
            formDataGetVO.setHeadList(explainList);
            formDataGetVO.setData(data);
            PaasFormEntity paasFormEntity = new PaasFormEntity();
            paasFormEntity.setId(0L);
            formDataGetVO.setPaasFormEntity(paasFormEntity);
        } catch (XbbException e) {
            throw e;
        } catch (Exception e) {
            LOG.error("知识库详情.get 出错", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
        }
        return formDataGetVO;
    }

    @Override
    public FormDataGetVO appKnowledgeDetail(FormDataGetDTO formDataGetDTO) throws XbbException {
        FormDataGetVO formDataGetVO = new FormDataGetVO();
        try {
            Long id = formDataGetDTO.getDataId();
            String corpid = formDataGetDTO.getCorpid();
            Integer businessType = formDataGetDTO.getBusinessType();
            KnowledgeDataEntity knowledgeDataEntity = knowledgeDataModel.getByKey(id, corpid);
            if (Objects.isNull(knowledgeDataEntity)){
                throw new XbbException(KnowledgeErrorCodeEnum.API_ERROR_320017.getCode(),KnowledgeErrorCodeEnum.API_ERROR_320017.getMsg());
            }
            List<String> userIds = new ArrayList<>();
            userIds.add(knowledgeDataEntity.getCreatorId());
            userIds.add(knowledgeDataEntity.getUpdateId());
            List<UserEntity> userEntitys = userModel.findEntitysByUserIds(userIds, corpid);
            Map<String, String> userIdAndNameMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            for (UserEntity entity : userEntitys) {
                userIdAndNameMap.put(entity.getUserId(), entity.getName());
            }
            //获取目录
            KnowledgeCatalogueEntity knowledgeCatalogueEntity = knowledgeCatalogueModel.getByKey(knowledgeDataEntity.getCatalogueId(), corpid);
            //获取表单解释
            PaasFormExplainEntity paasFormExplainEntity = paasFormExplainModel.getByBusinessType(businessType, "0");
            if (paasFormExplainEntity == null) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_EXPLAIN_NOT_EXIST);
            }
            List<FieldAttrEntity> explainList = JSONArray.parseArray(paasFormExplainEntity.getExplains(), FieldAttrEntity.class);
            //formList数据组装
            PaasFormDataEntityExt paasFormDataEntityExt = new PaasFormDataEntityExt();
            paasFormDataEntityExt.setId(knowledgeDataEntity.getId());
            paasFormDataEntityExt.setDataId(knowledgeDataEntity.getId());
            paasFormDataEntityExt.setCorpid(knowledgeDataEntity.getCorpid());
            paasFormDataEntityExt.setBusinessType(businessType);
            JSONObject data = JSONObject.parseObject(JSONObject.toJSONString(knowledgeDataEntity));
            if (Objects.nonNull(knowledgeDataEntity.getKeywords()) && CollectionsUtil.isNotEmpty(JSONArray.parseArray(knowledgeDataEntity.getKeywords(), String.class))) {
                String keyword = Joiner.on("、").join(JSONArray.parseArray(knowledgeDataEntity.getKeywords(), String.class));
                data.put(KnowledgeDataEnum.KEYWORDS.getAttr(), keyword);
            } else {
                data.put(KnowledgeDataEnum.KEYWORDS.getAttr(), "");
            }
            if (Objects.nonNull(knowledgeDataEntity.getExpandConsult()) && CollectionsUtil.isNotEmpty(JSONArray.parseArray(knowledgeDataEntity.getExpandConsult(), String.class))) {
                data.put(KnowledgeDataEnum.EXPAND_CONSULT.getAttr(), JSONArray.parseArray(knowledgeDataEntity.getExpandConsult(), String.class));
            } else {
                data.put(KnowledgeDataEnum.EXPAND_CONSULT.getAttr(), new ArrayList<>());
            }
            String appendixStr = knowledgeDataEntity.getAppendix();
            if (StringUtil.isNotEmpty(appendixStr)) {
                List<PaasAttachmentEntityExt> appendix = JSONArray.parseArray(appendixStr, PaasAttachmentEntityExt.class);
                data.put(KnowledgeDataEnum.APPENDIX.getAttr(), appendix);
            }
            // 标签
            JSONArray tags = new JSONArray();
            if (Objects.nonNull(knowledgeDataEntity.getLabel()) && CollectionsUtil.isNotEmpty(JSONArray.parseArray(knowledgeDataEntity.getLabel(), String.class))) {
                Map<String, Object> paramMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                paramMap.put("corpid", corpid);
                paramMap.put("del", 0);
                paramMap.put("idIn", JSONArray.parseArray(knowledgeDataEntity.getLabel(), String.class));
                List<KnowledgeTagEntity> knowledgeTagEntities = knowledgeTagModel.findEntitys(paramMap);
                for (KnowledgeTagEntity knowledgeTagEntity : knowledgeTagEntities) {
                    JSONObject object = new JSONObject();
                    if (Objects.nonNull(knowledgeTagEntity)) {
                        object.put("id", knowledgeTagEntity.getId());
                        object.put("name", knowledgeTagEntity.getName());
                        object.put("parentTagId", knowledgeTagEntity.getParentId());
                        object.put("color", knowledgeTagEntity.getColor());
                        tags.add(object);
                    }
                }
            }
            data.put(KnowledgeDataEnum.CONTENT.getAttr(), JSONArray.parseArray(knowledgeDataEntity.getContentArray(), KnowledgeContentDTO.class));
            data.put(KnowledgeDataEnum.LABEL.getAttr(), tags);
            data.put(KnowledgeDataEnum.CREATOR_ID.getAttr(), userIdAndNameMap.get(knowledgeDataEntity.getCreatorId()));
            data.put(KnowledgeDataEnum.UPDATE_ID.getAttr(), userIdAndNameMap.get(knowledgeDataEntity.getUpdateId()));
            data.put(KnowledgeDataEnum.CATALOGUE.getAttr(), knowledgeCatalogueEntity.getName());
            data.put(KnowledgeDataEnum.STATUS.getAttr(), KnowledgeDataStatusEnum.getByCode(knowledgeDataEntity.getStatus()));
            paasFormDataEntityExt.setData(data);
            formDataGetVO.setFormList(paasFormDataEntityExt);
            formDataGetVO.setHeadList(explainList);
            formDataGetVO.setData(data);
            PaasFormEntity paasFormEntity = new PaasFormEntity();
            formDataGetVO.setPaasFormEntity(paasFormEntity);
        } catch (XbbException e) {
            throw e;
        } catch (Exception e) {
            LOG.error("知识库详情.get 出错", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
        }
        return formDataGetVO;
    }

    /**
     * 将Excel数据格式化成表单保存需要的JSON格式的数据
     *
     * @param importFormDataDTO 导入入参
     * @param titlePojoList     标题
     * @param rowGroupPojo      一个表单对应的一组Excel填写的数据
     * @param fieldAttrList     解释
     * @return FormDataAddDTO
     * @throws XbbException XbbException
     */
    @Override
    public FormDataAddDTO formatExcelValue(ImportFormDataDTO importFormDataDTO, List<CellTitlePojo> titlePojoList, RowGroupPojo rowGroupPojo, List<FieldAttrEntityForImport> fieldAttrList) throws XbbException {
        FormDataAddDTO formDataAddDTO = new FormDataAddDTO();
        BeanUtil.copyProperties(importFormDataDTO, formDataAddDTO);
        // data 数据
        JSONObject dataJson = new JSONObject();
        List<List<CellValuePojo>> rowValueList = rowGroupPojo.getRowValueList();
        // 分组的第一条数据作为给实体对象赋值的数据
        List<CellValuePojo> cellValueList = rowValueList.get(0);
        // 遍历数据
        for (FieldAttrEntityForImport fieldAttrEntityForImport : fieldAttrList) {
            String attr = fieldAttrEntityForImport.getAttr();
            String attrName = fieldAttrEntityForImport.getAttrName();
            Integer columnIndex = importHelper.getColumnIndexByTitle(titlePojoList, attrName, null);
            Object cellValue = importHelper.getValueByColumnIndex(cellValueList, columnIndex);
            if (Objects.isNull(cellValue) || StringUtil.isEmpty(cellValue.toString())) {
                continue;
            }
            if (ImportHelper.commonHandleFieldType.contains(fieldAttrEntityForImport.getFieldType())) {
                importHelper.formatCommonField(dataJson, fieldAttrEntityForImport, cellValue);
            } else {
                dataJson.put(attr, cellValue);
            }
        }
        formDataAddDTO.setDataList(dataJson);
        return formDataAddDTO;
    }

    @Override
    public void importKnowledges(FormDataAddDTO formDataAddDTO) throws XbbException {
        FormDataAddVO formDataAddVO = new FormDataAddVO();
        //校验知识条目最大数量
        Map<String, Object> paramMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        paramMap.put("corpid", formDataAddDTO.getCorpid());
        paramMap.put("del", 0);
        paramMap.put("knowledgeBaseId", formDataAddDTO.getKnowledgeBaseId());
        Integer count = knowledgeDataModel.getEntitysCount(paramMap);
        if (count >= BasicConstant.KNOWLEDGE_DATA_HC) {
            throw new XbbException(KnowledgeErrorCodeEnum.API_ERROR_320015.getCode(),KnowledgeErrorCodeEnum.API_ERROR_320015.getMsg());
        }
        KnowledgeAddDTO knowledgeAddDTO = new KnowledgeAddDTO();
        JSONObject dataList = formDataAddDTO.getDataList();
        knowledgeAddDTO.setKnowledgeBaseId(formDataAddDTO.getKnowledgeBaseId());
        knowledgeAddDTO.setCorpid(formDataAddDTO.getCorpid());
        knowledgeAddDTO.setUserId(formDataAddDTO.getUserId());
        if (Objects.isNull(dataList.get(KnowledgeDataEnum.CONTENT.getAttr()))) {
            throw new XbbException(KnowledgeErrorCodeEnum.API_ERROR_320008.getCode(),KnowledgeErrorCodeEnum.API_ERROR_320008.getMsg());
        }
        if (Objects.isNull(dataList.get(KnowledgeDataEnum.TITLE.getAttr()))) {
            throw new XbbException(KnowledgeErrorCodeEnum.API_ERROR_320009.getCode(),KnowledgeErrorCodeEnum.API_ERROR_320009.getMsg());
        }
        if (Objects.isNull(dataList.get(KnowledgeDataEnum.CATALOGUE.getAttr()))) {
            throw new XbbException(KnowledgeErrorCodeEnum.API_ERROR_320010.getCode(),KnowledgeErrorCodeEnum.API_ERROR_320010.getMsg());
        }
        //获取目录
        paramMap.clear();
        paramMap.put("name", dataList.get(KnowledgeDataEnum.CATALOGUE.getAttr()));
        paramMap.put("corpid", formDataAddDTO.getCorpid());
        paramMap.put("del", 0);
        List<KnowledgeCatalogueEntity> catalogueEntities = knowledgeCatalogueModel.findEntitys(paramMap);
        if (CollectionsUtil.isEmpty(catalogueEntities)) {
            throw new XbbException(KnowledgeErrorCodeEnum.API_ERROR_320011.getCode(),KnowledgeErrorCodeEnum.API_ERROR_320011.getMsg());
        }
        if (Objects.isNull(dataList.get(KnowledgeDataEnum.STATUS.getAttr()))) {
            knowledgeAddDTO.setStatus(KnowledgeDataStatusEnum.ENABLE.getCode());
        } else {
            if (Objects.equals(dataList.get(KnowledgeDataEnum.STATUS.getAttr()), "启用")) {
                knowledgeAddDTO.setStatus(KnowledgeDataStatusEnum.ENABLE.getCode());
            } else if (Objects.equals(dataList.get(KnowledgeDataEnum.STATUS.getAttr()), "停用")) {
                knowledgeAddDTO.setStatus(KnowledgeDataStatusEnum.BLOCK_UP.getCode());
            } else {
                throw new XbbException(KnowledgeErrorCodeEnum.API_ERROR_320012.getCode(),KnowledgeErrorCodeEnum.API_ERROR_320012.getMsg());
            }
        }
        if (Objects.nonNull(dataList.get(KnowledgeDataEnum.KEYWORDS.getAttr()))) {
            String keyword = dataList.getString(KnowledgeDataEnum.KEYWORDS.getAttr());
            if (StringUtil.isNotEmpty(keyword)) {
                List<String> result = Arrays.asList(keyword.split("，"));
                knowledgeAddDTO.setKeywords(result);
            }
        }
        if (Objects.nonNull(dataList.get(KnowledgeDataEnum.EXPAND_CONSULT.getAttr()))) {
            String expandConsult = dataList.getString(KnowledgeDataEnum.EXPAND_CONSULT.getAttr());
            if (StringUtil.isNotEmpty(expandConsult)){
                List<String> result = Arrays.asList(expandConsult.split("，"));
                knowledgeAddDTO.setExpandConsult(result);
            }
        }
        knowledgeAddDTO.setContent(dataList.getString(KnowledgeDataEnum.CONTENT.getAttr()));
        //拼接建议回复参数
        List<KnowledgeContentDTO> knowledgeContentDTOS = new ArrayList<>();
        KnowledgeContentDTO knowledgeContentDTO = new KnowledgeContentDTO();
        knowledgeContentDTO.setContent(knowledgeAddDTO.getContent());
        knowledgeContentDTO.setIndex(0);
        knowledgeContentDTO.setType(KnowledgeContentTypeEnum.TEXT.getCode());
        knowledgeContentDTOS.add(knowledgeContentDTO);
        knowledgeAddDTO.setContentArray(knowledgeContentDTOS);
        knowledgeAddDTO.setTitle(dataList.getString(KnowledgeDataEnum.TITLE.getAttr()));
        knowledgeAddDTO.setCatalogueId(catalogueEntities.get(0).getId());
        this.knowledgeCheck(knowledgeAddDTO);
        KnowledgeDataEntity knowledgeDataEntity = new KnowledgeDataEntity();
        knowledgeDataEntity.setTitle(knowledgeAddDTO.getTitle());
        //目录
        knowledgeDataEntity.setCatalogueId(knowledgeAddDTO.getCatalogueId());
        knowledgeDataEntity.setCorpid(knowledgeAddDTO.getCorpid());
        //关键词
        if (CollectionsUtil.isNotEmpty(knowledgeAddDTO.getKeywords())) {
            knowledgeDataEntity.setKeywords(JSONObject.toJSONString(knowledgeAddDTO.getKeywords()));
        }
        //拓展问法
        if (CollectionsUtil.isNotEmpty(knowledgeAddDTO.getExpandConsult())) {
            knowledgeDataEntity.setExpandConsult(JSONObject.toJSONString(knowledgeAddDTO.getExpandConsult()));
        }
        //状态
        knowledgeDataEntity.setStatus(knowledgeAddDTO.getStatus());
        knowledgeDataEntity.setDel(DelEnum.NORMAL.getDel());
        //处理建议回复
        String content = getContentStringByContentArray(knowledgeAddDTO.getContentArray());
        knowledgeDataEntity.setContent(content);
        knowledgeDataEntity.setContentArray(JSONObject.toJSONString(knowledgeAddDTO.getContentArray()));
        knowledgeDataEntity.setKnowledgeBaseId(knowledgeAddDTO.getKnowledgeBaseId());
        knowledgeDataEntity.setUsageCount(0L);
        knowledgeDataEntity.setUpdateId(knowledgeAddDTO.getUserId());
        knowledgeDataEntity.setCreatorId(knowledgeAddDTO.getUserId());
        knowledgeDataModel.insert(knowledgeDataEntity);
        //插入es
        KnowledgeEsAddDTO knowledgeEsAddDTO = this.initAddEsData(knowledgeDataEntity, knowledgeAddDTO);
        InsertDTO insertDTO = paasEsModel.getSaveDTO(knowledgeEsAddDTO, IndexTypeEnum.IDX_SAAS_KNOWLEDGE_DATA);
        paasEsModel.insert(insertDTO);
        formDataAddVO.setMsg(I18nMessageUtil.getMessage(MessageConstant.FORM_ADD_RETURN_MSG));
        formDataAddVO.setCode(PaasConstant.FORM_ADD_RETURN_CODE);
        formDataAddVO.setDataId(knowledgeDataEntity.getId());
        formDataAddVO.setFormDataId(knowledgeDataEntity.getId());
    }

    @Override
    public BaseVO batchRemoveTag(BatchDealTagDTO batchDealTagDTO) throws XbbException {
        BaseVO baseVO = new BaseVO();
        String corpid = batchDealTagDTO.getCorpid();
        String userId = batchDealTagDTO.getUserId();
        String loginUserName = batchDealTagDTO.getLoginUserName();
        List<Long> idList = new ArrayList<>();
        List<String> knowledgeTitleList = new ArrayList<>();
        //获取知识库
        KnowledgeBaseEntity knowledgeBaseEntity = knowledgeBaseModel.getByKey(batchDealTagDTO.getKnowledgeBaseId(), corpid);
        List<KnowledgeTagEntity> tagEntities = knowledgeTagModel.getByTagIdList(batchDealTagDTO.getTagIdList(), corpid);
        List<String> tagNameList = tagEntities.stream().map(KnowledgeTagEntity::getName).collect(Collectors.toList());
        StringBuilder tagNameListStr = new StringBuilder();
        StringUtil.arrayBuilderAppendSuffix(tagNameListStr, ",", tagNameList);
        Map<String, Object> paramMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        paramMap.put("corpid", corpid);
        paramMap.put("del", 0);
        paramMap.put("idIn", batchDealTagDTO.getDataIdList());
        List<KnowledgeDataEntity> knowledgeDataUpdate = new ArrayList<>();
        List<KnowledgeDataEntity> knowledgeDataEntities = knowledgeDataModel.findEntitys(paramMap);
        Map<String, Object> map = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        map.put(StringConstant.UPDATE_TIME, DateTimeUtil.getInt());
        map.put(KnowledgeDataEnum.UPDATE_ID.getAttr(), userId);
        List<InsertDTO> insertDTOList = new ArrayList<>();
        for (KnowledgeDataEntity knowledgeDataEntity : knowledgeDataEntities) {
            knowledgeTitleList.add(knowledgeDataEntity.getTitle());
            idList.add(knowledgeDataEntity.getId());
            if (Objects.isNull(knowledgeDataEntity.getLabel())) {
                continue;
            }
            List<Long> tags = JSONArray.parseArray(knowledgeDataEntity.getLabel(), Long.class);
            if (CollectionsUtil.isEmpty(tags)){
                continue;
            }
            List<Long> reduceList = tags.stream().filter(item -> !batchDealTagDTO.getTagIdList().contains(item)).collect(Collectors.toList());
            InsertDTO insertDTO = new InsertDTO();
            insertDTO.setEsId(corpid + "_" + knowledgeDataEntity.getId());
            insertDTO.setIndexTypeEnum(IndexTypeEnum.IDX_SAAS_KNOWLEDGE_DATA);
            insertDTO.setIndex(IndexTypeEnum.IDX_SAAS_KNOWLEDGE_DATA.getIndex());
            insertDTO.setType(IndexTypeEnum.IDX_SAAS_KNOWLEDGE_DATA.getType());
            map.put(KnowledgeDataEnum.LABEL.getAttr(), reduceList);
            insertDTO.setSource(map);
            insertDTOList.add(insertDTO);
            knowledgeDataEntity.setUpdateId(userId);
            knowledgeDataEntity.setLabel(JSONArray.toJSONString(reduceList));
            knowledgeDataEntity.setUpdateTime(DateTimeUtil.getInt());
            knowledgeDataUpdate.add(knowledgeDataEntity);
        }
        if (!knowledgeDataUpdate.isEmpty()) {
            knowledgeDataModel.updateBatch(knowledgeDataUpdate, corpid);
            paasEsModel.updateBatch(insertDTOList);
        }
        // 记录移标签日志
        StringBuilder knowledgeTitleStr = new StringBuilder();
        StringUtil.arrayBuilderAppendSuffix(knowledgeTitleStr, ",", knowledgeTitleList);
        String memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_REMOVE_KNOWLEDGE_TAG), loginUserName, knowledgeBaseEntity.getKnowledgeName(), knowledgeTitleStr.toString(), tagNameListStr.toString());
        mongoLogHelp.buildLog4DetailArr(null, corpid, userId, loginUserName, OperateModuleTypeEnum.getByAlias(OperateModuleTypeEnum.KNOWLEDGE_BASE.getAlias()), OperateTypeEnum.REMOVE_LABEL, JSONArray.toJSONString(idList), knowledgeTitleStr.toString(), memo, batchDealTagDTO.getHttpHeader());
        return baseVO;
    }

    @Override
    public BaseVO batchAddTag(BatchDealTagDTO batchDealTagDTO) throws XbbException {
        if (batchDealTagDTO.getTagIdList().size() > BasicConstant.KNOWLEDGE_KEYWORD_HC) {
            throw new XbbException(KnowledgeErrorCodeEnum.API_ERROR_320007.getCode(),KnowledgeErrorCodeEnum.API_ERROR_320007.getMsg());
        }
        BaseVO baseVO = new BaseVO();
        String corpid = batchDealTagDTO.getCorpid();
        String userId = batchDealTagDTO.getUserId();
        String loginUserName = batchDealTagDTO.getLoginUserName();
        List<Long> idList = new ArrayList<>();
        List<String> knowledgeTitleList = new ArrayList<>();
        //获取知识库
        KnowledgeBaseEntity knowledgeBaseEntity = knowledgeBaseModel.getByKey(batchDealTagDTO.getKnowledgeBaseId(), corpid);
        List<KnowledgeTagEntity> tagEntities = knowledgeTagModel.getByTagIdList(batchDealTagDTO.getTagIdList(), corpid);
        List<String> tagNameList = tagEntities.stream().map(KnowledgeTagEntity::getName).collect(Collectors.toList());
        StringBuilder tagNameListStr = new StringBuilder();
        StringUtil.arrayBuilderAppendSuffix(tagNameListStr, ",", tagNameList);
        Map<String, Object> paramMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        paramMap.put("corpid", corpid);
        paramMap.put("del", 0);
        paramMap.put("idIn", batchDealTagDTO.getDataIdList());
        List<KnowledgeDataEntity> knowledgeDataUpdate = new ArrayList<>();
        List<KnowledgeDataEntity> knowledgeDataEntities = knowledgeDataModel.findEntitys(paramMap);
        List<InsertDTO> insertDTOList = new ArrayList<>();
        for (KnowledgeDataEntity knowledgeDataEntity : knowledgeDataEntities) {
            knowledgeTitleList.add(knowledgeDataEntity.getTitle());
            idList.add(knowledgeDataEntity.getId());
            InsertDTO insertDTO = new InsertDTO();
            insertDTO.setEsId(corpid + "_" + knowledgeDataEntity.getId());
            insertDTO.setIndexTypeEnum(IndexTypeEnum.IDX_SAAS_KNOWLEDGE_DATA);
            insertDTO.setIndex(IndexTypeEnum.IDX_SAAS_KNOWLEDGE_DATA.getIndex());
            insertDTO.setType(IndexTypeEnum.IDX_SAAS_KNOWLEDGE_DATA.getType());
            knowledgeDataEntity.setUpdateId(userId);
            knowledgeDataEntity.setUpdateTime(DateTimeUtil.getInt());
            Map<String, Object> map = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            map.put(StringConstant.UPDATE_TIME, DateTimeUtil.getInt());
            map.put(KnowledgeDataEnum.UPDATE_ID.getAttr(), userId);
            if (Objects.isNull(knowledgeDataEntity.getLabel())) {
                map.put(KnowledgeDataEnum.LABEL.getAttr(), batchDealTagDTO.getTagIdList());
                knowledgeDataEntity.setLabel(JSONArray.toJSONString(batchDealTagDTO.getTagIdList()));
            } else {
                List<Long> tags = JSONArray.parseArray(knowledgeDataEntity.getLabel(), Long.class);
                tags.addAll(batchDealTagDTO.getTagIdList());
                tags = tags.stream().distinct().collect(Collectors.toList());
                if (tags.size() > BasicConstant.KNOWLEDGE_KEYWORD_HC) {
                    throw new XbbException(KnowledgeErrorCodeEnum.API_ERROR_320007.getCode(), KnowledgeErrorCodeEnum.API_ERROR_320007.getMsg());
                }
                knowledgeDataEntity.setLabel(JSONArray.toJSONString(tags));
                map.put(KnowledgeDataEnum.LABEL.getAttr(), tags);
            }
            insertDTO.setSource(map);
            insertDTOList.add(insertDTO);
            knowledgeDataUpdate.add(knowledgeDataEntity);
        }
        if (!knowledgeDataUpdate.isEmpty()) {
            knowledgeDataModel.updateBatch(knowledgeDataUpdate, corpid);
            paasEsModel.updateBatch(insertDTOList);
        }
        // 记录标签日志
        StringBuilder knowledgeTitleStr = new StringBuilder();
        StringUtil.arrayBuilderAppendSuffix(knowledgeTitleStr, ",", knowledgeTitleList);
        String memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_ADD_KNOWLEDGE_TAG), loginUserName, knowledgeBaseEntity.getKnowledgeName(), knowledgeTitleStr.toString(), tagNameListStr.toString());
        mongoLogHelp.buildLog4DetailArr(null, corpid, userId, loginUserName, OperateModuleTypeEnum.getByAlias(OperateModuleTypeEnum.KNOWLEDGE_BASE.getAlias()), OperateTypeEnum.ADD_LABEL, JSONArray.toJSONString(idList), knowledgeTitleStr.toString(), memo, batchDealTagDTO.getHttpHeader());
        return baseVO;
    }

    /**
     * 处理赋值
     *
     * @param knowledgeAddDTO
     * @param knowledgeDataEntity
     */
    private void dealKnowledgeDataData(KnowledgeAddDTO knowledgeAddDTO, KnowledgeDataEntity knowledgeDataEntity) {
        knowledgeDataEntity.setTitle(knowledgeAddDTO.getTitle());
        if (CollectionsUtil.isNotEmpty(knowledgeAddDTO.getAppendix())) {
            knowledgeDataEntity.setAppendix(JSONObject.toJSONString(knowledgeAddDTO.getAppendix()));
        }
        //目录
        knowledgeDataEntity.setCatalogueId(knowledgeAddDTO.getCatalogueId());
        knowledgeDataEntity.setCorpid(knowledgeAddDTO.getCorpid());
        //关键词
        if (CollectionsUtil.isNotEmpty(knowledgeAddDTO.getKeywords())) {
            knowledgeDataEntity.setKeywords(JSONObject.toJSONString(knowledgeAddDTO.getKeywords()));
        }
        //拓展问法
        if (CollectionsUtil.isNotEmpty(knowledgeAddDTO.getExpandConsult())) {
            knowledgeDataEntity.setExpandConsult(JSONObject.toJSONString(knowledgeAddDTO.getExpandConsult()));
        }
        //状态
        knowledgeDataEntity.setStatus(KnowledgeDataStatusEnum.ENABLE.getCode());
        knowledgeDataEntity.setDel(DelEnum.NORMAL.getDel());
        //标签
        if (CollectionsUtil.isNotEmpty(knowledgeAddDTO.getLabel())) {
            knowledgeDataEntity.setLabel(JSONObject.toJSONString(knowledgeAddDTO.getLabel()));
        }
        //处理建议回复
        String content = getContentStringByContentArray(knowledgeAddDTO.getContentArray());
        knowledgeDataEntity.setContent(content);
        knowledgeDataEntity.setContentArray(JSONObject.toJSONString(knowledgeAddDTO.getContentArray()));
        knowledgeDataEntity.setKnowledgeBaseId(knowledgeAddDTO.getKnowledgeBaseId());
        knowledgeDataEntity.setUsageCount(0L);
        knowledgeDataEntity.setUpdateId(knowledgeAddDTO.getUserId());
        knowledgeDataEntity.setCreatorId(knowledgeAddDTO.getUserId());
    }

    /**
     * 初始化插入ES数据
     *
     * @param knowledgeAddDTO
     * @param knowledgeDataEntity
     */
    private KnowledgeEsAddDTO initAddEsData(KnowledgeDataEntity knowledgeDataEntity, KnowledgeAddDTO knowledgeAddDTO) {
        KnowledgeEsAddDTO knowledgeEsAddDTO = new KnowledgeEsAddDTO();
        knowledgeEsAddDTO.setContent(knowledgeDataEntity.getContent());
        knowledgeEsAddDTO.setKnowledgeBaseId((knowledgeDataEntity.getKnowledgeBaseId()));
        knowledgeEsAddDTO.setTitle(knowledgeDataEntity.getTitle());
        if (CollectionsUtil.isNotEmpty(knowledgeAddDTO.getExpandConsult())) {
            knowledgeEsAddDTO.setExpandConsult(knowledgeAddDTO.getExpandConsult());
        } else {
            knowledgeEsAddDTO.setExpandConsult(new ArrayList<>());
        }
        if (CollectionsUtil.isNotEmpty(knowledgeAddDTO.getLabel())) {
            knowledgeEsAddDTO.setLabel(knowledgeAddDTO.getLabel());
        } else {
            knowledgeEsAddDTO.setLabel(new ArrayList<>());
        }
        if (CollectionsUtil.isNotEmpty(knowledgeAddDTO.getKeywords())) {
            knowledgeEsAddDTO.setKeywords(knowledgeAddDTO.getKeywords());
        } else {
            knowledgeEsAddDTO.setKeywords(new ArrayList<>());
        }
        if (CollectionsUtil.isNotEmpty(knowledgeAddDTO.getAppendix())) {
            knowledgeEsAddDTO.setAppendix(JSONObject.toJSONString(knowledgeAddDTO.getAppendix()));
        } else {
            knowledgeEsAddDTO.setAppendix("[]");
        }
        knowledgeEsAddDTO.setId(knowledgeDataEntity.getId());
        knowledgeEsAddDTO.setCatalogueId(knowledgeDataEntity.getCatalogueId());
        knowledgeEsAddDTO.setAddTime(knowledgeDataEntity.getAddTime());
        knowledgeEsAddDTO.setUpdateTime(knowledgeDataEntity.getUpdateTime());
        knowledgeEsAddDTO.setCreatorId(knowledgeDataEntity.getCreatorId());
        knowledgeEsAddDTO.setUpdateId(knowledgeDataEntity.getUpdateId());
        knowledgeEsAddDTO.setCorpid(knowledgeDataEntity.getCorpid());
        knowledgeEsAddDTO.setDataId(knowledgeDataEntity.getId());
        knowledgeEsAddDTO.setDel(knowledgeDataEntity.getDel());
        knowledgeEsAddDTO.setStatus(knowledgeDataEntity.getStatus());
        knowledgeEsAddDTO.setUsageCount(knowledgeDataEntity.getUsageCount());
        return knowledgeEsAddDTO;
    }

    /**
     * 知识条目校验
     *
     * @param knowledgeAddDTO 知识数据
     * @throws XbbException
     */
    private void knowledgeCheck(KnowledgeAddDTO knowledgeAddDTO) throws XbbException {
        if (CollectionsUtil.isNotEmpty(knowledgeAddDTO.getAppendix())) {
            if (StringUtil.isEmpty(knowledgeAddDTO.getAppendix().get(0).getAttachIndex())) {
                throw new XbbException(KnowledgeErrorCodeEnum.API_ERROR_320020.getCode(), KnowledgeErrorCodeEnum.API_ERROR_320020.getMsg());
            }
        }
        //校验知识条目最大数量，新建才需要校验
        if (Objects.nonNull(knowledgeAddDTO.getKnowledgeBaseId())) {
            Map<String, Object> paramMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            paramMap.put("corpid", knowledgeAddDTO.getCorpid());
            paramMap.put("del", 0);
            paramMap.put("knowledgeBaseId", knowledgeAddDTO.getKnowledgeBaseId());
            Integer count = knowledgeDataModel.getEntitysCount(paramMap);
            if (count >= BasicConstant.KNOWLEDGE_DATA_HC) {
                throw new XbbException(KnowledgeErrorCodeEnum.API_ERROR_320015.getCode(), KnowledgeErrorCodeEnum.API_ERROR_320015.getMsg());
            }
        }
        List<KnowledgeContentDTO> knowledgeContentDTOS = knowledgeAddDTO.getContentArray();
        StringBuffer stringBuffer = new StringBuffer();
        for (KnowledgeContentDTO knowledgeContentDTO : knowledgeContentDTOS) {
            if (Objects.equals(knowledgeContentDTO.getType(), KnowledgeContentTypeEnum.TEXT.getCode())) {
                stringBuffer.append(knowledgeContentDTO.getContent());
            }
        }
        String checkContent = stringBuffer.toString();
        if (checkContent.length() > BasicConstant.KNOWLEDGE_CONTENT_HC) {
            throw new XbbException(KnowledgeErrorCodeEnum.API_ERROR_320003.getCode(), KnowledgeErrorCodeEnum.API_ERROR_320003.getMsg());
        }
        //附件校验
        if (CollectionsUtil.isNotEmpty(knowledgeAddDTO.getAppendix())) {
            if (knowledgeAddDTO.getAppendix().size() > BasicConstant.KNOWLEDGE_FILE_HC) {
                throw new XbbException(KnowledgeErrorCodeEnum.API_ERROR_320019.getCode(), KnowledgeErrorCodeEnum.API_ERROR_320019.getMsg());
            }
        }
        if (CollectionsUtil.isNotEmpty(knowledgeAddDTO.getKeywords())) {
            for (String keywords : knowledgeAddDTO.getKeywords()) {
                if (keywords.length() > BasicConstant.KNOWLEDGE_KEYWORD_NUMBER_HC) {
                    throw new XbbException(KnowledgeErrorCodeEnum.API_ERROR_320004.getCode(), KnowledgeErrorCodeEnum.API_ERROR_320004.getMsg());
                }
            }
            if (knowledgeAddDTO.getKeywords().size() > BasicConstant.KNOWLEDGE_KEYWORD_HC) {
                throw new XbbException(KnowledgeErrorCodeEnum.API_ERROR_320014.getCode(), KnowledgeErrorCodeEnum.API_ERROR_320014.getMsg());
            }
        }
        if (CollectionsUtil.isNotEmpty(knowledgeAddDTO.getExpandConsult())) {
            for (String expandConsult : knowledgeAddDTO.getExpandConsult()) {
                if (expandConsult.length() > BasicConstant.KNOWLEDGE_TITLE_HC) {
                    throw new XbbException(KnowledgeErrorCodeEnum.API_ERROR_320005.getCode(), KnowledgeErrorCodeEnum.API_ERROR_320005.getMsg());
                }
            }
            if (knowledgeAddDTO.getExpandConsult().size() > BasicConstant.KNOWLEDGE_KEYWORD_HC) {
                throw new XbbException(KnowledgeErrorCodeEnum.API_ERROR_320014.getCode(), KnowledgeErrorCodeEnum.API_ERROR_320014.getMsg());
            }
        }
        if (Objects.nonNull(knowledgeAddDTO.getTitle())) {
            if (knowledgeAddDTO.getTitle().length() > BasicConstant.KNOWLEDGE_TITLE_HC) {
                throw new XbbException(KnowledgeErrorCodeEnum.API_ERROR_320006.getCode(), KnowledgeErrorCodeEnum.API_ERROR_320006.getMsg());
            }
        }
        if (CollectionsUtil.isNotEmpty(knowledgeAddDTO.getLabel())) {
            if (knowledgeAddDTO.getLabel().size() > BasicConstant.KNOWLEDGE_KEYWORD_HC) {
                throw new XbbException(KnowledgeErrorCodeEnum.API_ERROR_320007.getCode(), KnowledgeErrorCodeEnum.API_ERROR_320007.getMsg());
            }
        }
    }

    /**
     * 处理建议回复中的空格
     *
     * @param knowledgeContentDTOList
     * @return
     */
    private String getContentStringByContentArray(List<KnowledgeContentDTO> knowledgeContentDTOList) {
        StringBuffer contentBuffer = new StringBuffer();
        for (KnowledgeContentDTO knowledgeContentDTO : knowledgeContentDTOList) {
            if (Objects.equals(knowledgeContentDTO.getType(), KnowledgeContentTypeEnum.TEXT.getCode())) {
                String content = knowledgeContentDTO.getContent();
                if (StringUtil.isNotEmpty(content) && StringUtil.isNotEmpty(content.trim())) {
                    content = content.replaceAll("&nbsp;", "");
                }
                contentBuffer.append(content.trim());
            }
        }
        return contentBuffer.toString();
    }


    /**
     * @Author mingliang
     * @Description 更新知识库更新时间
     * @Date 2022/8/22 15:20
     * @param knowledgeId
     * @param corpid
     **/
    private void updateKnowledgeUpdateTime(Long knowledgeId,String corpid) {
        KnowledgeBaseEntity knowledgeBaseEntity = new KnowledgeBaseEntity();
        knowledgeBaseEntity.setId(knowledgeId);
        knowledgeBaseEntity.setCorpid(corpid);
        knowledgeBaseModel.update(knowledgeBaseEntity);
    }

    private void insertCabinetFile(String corpid, String userId, Long id, PaasAttachmentEntityExt paasAttachmentEntityExt) throws XbbException {
        CabinetFileEntity cabinetFileEntity = new CabinetFileEntity();
        cabinetFileEntity.setCorpid(corpid);
        cabinetFileEntity.setUserId(userId);
        cabinetFileEntity.setBusinessType(XbbRefTypeEnum.KNOWLEDGE_BASE.getCode());
        cabinetFileEntity.setDataId(id);
        cabinetFileEntity.setFilename(paasAttachmentEntityExt.getFilename());
        cabinetFileEntity.setAttachIndex(paasAttachmentEntityExt.getAttachIndex());
        cabinetFileEntity.setExt(paasAttachmentEntityExt.getExt());
        cabinetFileEntity.setSize(paasAttachmentEntityExt.getSize());
        cabinetFileEntity.setType(1);
        cabinetFileModel.insert(cabinetFileEntity);
    }
}
